Table of Contents
一、中文版
編寫一個函數來查找字符串數組中的最長公共前綴。
如果不存在公共前綴,返回空字符串 ""。
示例 1:
輸入: ["flower","flow","flight"]
輸出: "fl"
示例 2:
輸入: ["dog","racecar","car"]
輸出: ""
解釋: 輸入不存在公共前綴。
說明:
所有輸入只包含小寫字母 a-z 。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/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: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.
三、My answer
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs:
return ""
if len(strs) == 1:
return strs[0]
min_len = len(strs[0])
for item in strs:
if len(item) < min_len:
min_len = len(item)
i, j = 0 ,1
for i in range(min_len):
for j in range(1,len(strs)):
if strs[j][i] != strs[j-1][i]:
return strs[0][0:i]
if i == min_len-1 and j == len(strs)-1:
return strs[0][:min_len]
return ""
四、解題報告
數據結構:數組,字符串
算法:遍歷
實現:縱向遍歷。看 strs 數組中每一個字符串的第 i 位是否相同,如果相同則繼續,不同則返回結果。
注意:特判 i 和 j 都遍歷到最後一位時的情況,如果不加特判,那麼如 ["aa","a"] 就會出錯。