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
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