LeetCode(14) 最長公共字首

2021-08-28 02:36:04 字數 1504 閱讀 1402

描述

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

如果不存在公共字首,返回空字串 「」。

示例1:

輸入: ["flower","flow","flight"]

輸出: "fl"

示例2:
輸入: ["dog","racecar","car"]

輸出: ""

解釋: 輸入不存在公共字首。

說明

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

class

solution:

deflongestcommonprefix

(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)) =

set((1, 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

古德古德。

LeetCode14最長公共字首

編寫乙個函式來查詢字串陣列中最長的公共字首字串。例如 輸出 ab 比較乙個字串陣列的最長公共字首,遍歷整個字串陣列,建立乙個字串用來儲存當前最長公共字串,逐個比較,不斷更新公共字串內容。情況比較多,考慮周全,不然可能會陣列溢位。公共字串的長度和當前比較字串的長度大小的比較,避免陣列越界,還有空字串的...

LeetCode 14 最長公共字首

編寫乙個函式來查詢字串陣列中最長的公共字首字串。用第乙個字串s,比較strs的每個字串的公共字首,並記錄字首有m位,之後輸出s的前m位字元即可。但是在輸出過程中,使用了如下的賦值方式 for int i 0 i m i ans i s i 在string型別中,內部的成員是private的,所以不能...

LeetCode14 最長公共字首

題目描述 編寫乙個函式來查詢字串陣列中的最長公共字首。如果不存在公共字首,返回空字串 示例 1 輸入 flower flow flight 輸出 fl 示例 2 輸入 dog racecar car 輸出 解釋 輸入不存在公共字首。說明 所有輸入只包含小寫字母a z。如下 class solutio...