Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How LeetCode implements the longest common prefix

Shulou Source: shulou.com Published: 2022-06-01 13:21:54 09月12日 Update

This article mainly introduces LeetCode how to achieve the longest public prefix, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

one

Topic description

Find the longest common prefix in the string array and return it, otherwise return "". For example, enter ["flower", "flow", "flight"] and return "fl".

two

Answer to the question

Idea: the zip function in zip function python brings great convenience to the solution of this problem. The zip function packages the corresponding elements into tuples and returns a list of tuples the same length as the shortest object. The * operator means to extract the tuple into a list. Use an example to see what the zip function can achieve:

A = [1 print (zip (a) print (list (zip (a) print (list (zip (* zip (a)

Through the zip function, the characters corresponding to the position of each string are formed into tuples, and then the tuples are transformed into a collection of non-repetitive elements through the set function, and the final result can be obtained. The corresponding code is as follows:

Class Solution: def longestCommonPrefix (self, strs: List [str]): ans = "" for i in zip (* strs): if len (set (I)) = = 1: ans+=i [0] else: break return ans

Thank you for reading this article carefully. I hope the article "how to achieve the longest Public prefix in LeetCode" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Tags: Function article longest prefix character result string title same code value location example element interest at the same time object idea operator array Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Huawei MariaDB Redmi vpn