Longest common prefix (py)

Write a function to find the longest common prefix string array.

If there is no common prefix, it returns an empty string "."

Example 1:

Input: [ "flower", "flow ", "flight"]
Output: "fl"
Example 2:

Input: [ "dog", "racecar ", "car"]
Output: ""
Explanation: there is no input common prefix.
Description:

All input contains only lowercase letters az.

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/longest-common-prefix
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

 

python solution:

Because there python max, min can compare the size of the string ascii, max and min can be found directly strings, compare their common prefix that is the longest common prefix. Prefix max and the ratio of the presence of a large min, so look for the prefix min.

1 class Solution:
2     def longestCommonPrefix(self, strs: List[str]) -> str:
3         if not strs : return ""
4         s1=max(strs)
5         s2=min(strs)
6         for i,x in enumerate(s2):
7             if x != s1[i]:
8                 return s1[:i]
9         return s2
Results of the:
by
When execution: 24 ms, beat the 99.75% of users in all Python3 submission
Memory consumption: 13.2 MB, defeated 41.66% of users in all Python3 submission
 
See also the discussion after the discovery can be answered with zip
Str as the list is then input as a two-dimensional array, left-aligned longitudinal compression, and then to re-set for each use, after the traversal list is found before a common prefix element length is greater than 1
 1  def longestCommonPrefix(self, strs):
 2         if not strs: return ""
 3         ss = list(map(set, zip(*strs)))
 4         res = ""
 5         for i, x in enumerate(ss):
 6             x = list(x)
 7             if len(x) > 1:
 8                 break
 9             res = res + x[0]
10         return res

 

 

Guess you like

Origin www.cnblogs.com/zccfrancis/p/12185300.html