題目 : 14. Longest Common Prefix
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 ""
.
Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
1.
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
#建立空的ans字串存重複的字母
ans = ""
# 先將字串集做排序
strs = sorted(strs)
# 比對第一個字串(shortest)和最後一個字串(longest)
first = strs[0]
last = strs[-1]
#用for迴圈逐一比對
for i in range(min(len(first),len(last))):
if (first[i]!=last[i]):
return ans
ans = ans + first[i]
return ans