Promble
link: https://leetcode.com/problems/longest-common-prefix/description/
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string “”.
Input: strs = ["flower","flow","flight"]
Output: "fl"
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Approach 1
Thought
- def ans:str to store the final result
- sort the strs, because we only compare the first and last str
- num:int is the min length in strs
- def first:str and last:str
- loop i in range(num)
- if (first[i] != last[i]): return ans
- ans+=first[i]
- return ans
Code
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
ans = ""
strs = sorted(strs)
num = min([len(i) for i in strs])
first = strs[0]
last = strs[-1]
for i in range(num):
if (first[i] != last[i]):
return ans
ans += first[i]
return ans
Approach 2
Thought
- judge the len(strs) <= 1.
- def end, minl is 0 and min(len(strs))
- while end<minl
- loop i in range(1, len(strs))
- if strs[i][end] != strs[i-1][end]: return strs[0][:end]
- end += 1
- loop i in range(1, len(strs))
- return strs[0][:end]
Code
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if len(strs) <= 1:
return strs[0] if len(strs) == 1 else ""
end, minl = 0, min([len(s) for s in strs])
while end<minl:
for i in range(1, len(strs)):
if strs[i][end] != strs[i-1][end]:
return strs[0][:end]
end = end + 1
return strs[0][:end]