天天看點

《算法小白曆險記》3.最長公共字首【python-簡單】

🍅 粉絲專屬福利:履歷模闆、PPT模闆、學習資料、面試題庫。直接去文末領取

🍅 如覺得文章不錯,歡迎點贊、收藏、評論

題目:

編寫一個函數來查找字元串數組中的最長公共字首。

如果不存在公共字首,傳回空字元串 ""。

 

示例 1:

輸入:strs = ["flower","flow","flight"]
輸出:"fl"
示例 2:

輸入:strs = ["dog","racecar","car"]
輸出:""
解釋:輸入不存在公共字首。
 

提示:

1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] 僅由小寫英文字母組成      

來源:力扣(LeetCode)

連結:https://leetcode-cn.com/problems/longest-common-prefix

我的笨辦法:

思路:找出最短字元串,以此作為最大角标位。然後周遊對比第一個元素。

《算法小白曆險記》3.最長公共字首【python-簡單】
class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        com = ''
        str_min = min([len(str) for str in strs])
        for i in range(str_min):
            one = [str[i] for str in strs]
            if len(set(one))==1:
                com = com + one[0]
            else:
                break
        return com      

大神的辦法:

解題思路

先找出數組中字典序最小和最大的字元串,最長公共字首即為這兩個字元串的公共字首

《算法小白曆險記》3.最長公共字首【python-簡單】
class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs: return ""
        str0 = min(strs)
        str1 = max(strs)
        for i in range(len(str0)):
            if str0[i] != str1[i]:
                return str0[:i]
        return str0      

鬼才!可太秀了。

粉絲專屬福利