1. 程式人生 > >LeetCode(14)—— 最長公共字首

LeetCode(14)—— 最長公共字首

描述

編寫一個函式來查詢字串陣列中的最長公共字首。

如果不存在公共字首,返回空字串 “”。

示例1:
輸入: ["flower","flow","flight"]
輸出: "fl"
示例2:
輸入: ["dog","racecar","car"]
輸出: ""
解釋: 輸入不存在公共字首。
說明

所有輸入只包含小寫字母 a-z

so easy的題

class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
# 字串總個數 if len(strs) == 0: return "" index = 0 common_prefix = "" # 從第一個字串的第一個字元開始去試探 while True: try: ch = strs[0][index] # 匹配每個字串 for item in strs: if item[index] != ch: return
common_prefix # 繼續往下試探 index += 1 common_prefix += ch # 最短字串到底了 except IndexError: return common_prefix

plus

雖然是簡單題,不過看到一位仁兄巧妙的用了python中的zip()

zip的特點

a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9, 10]
zip(a, b, c) is =>
(1
, 4, 7) (2, 5, 8) (3, 6, 9) set((1, 1, 1)) = {'1'} set((1, 1, 2)) = {'1', '2'}

於是程式碼就可以這樣寫了:

 def longestCommonPrefix_use_zip(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        prefix = ''
        for _, item in enumerate(zip(*strs)):
            if len(set(item)) > 1:
                return prefix
            else:
                prefix += item[0]
        return prefix

古德古德。

作者地址:https://blog.csdn.net/github_37953781/article/details/73649713