n 種方法實現最長公共字首

2021-10-08 17:50:51 字數 1967 閱讀 9331

leetcode 14:最長公共字首

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

如果不存在公共字首,返回空字串''

將第乙個字串賦給字首prefix,然後依次比較每個字串,比較過程中更新字首。

def

longestcommonprefix

(strs):if

not strs:

return''

prefix = strs[0]

for s in strs[1:

]:while

not s.startswith(prefix)

: prefix = prefix[

:len

(prefix)-1

]ifnot prefix:

return

''return prefix

startswith()方法用於檢查字串是否是以指定子字串開頭,如果是則返回true,否則返回false

def

longestcommonprefix

(strs)

: prefix =

''for s in

zip(

*strs):if

len(

set(s))==

1:prefix += s[0]

else

:break

return prefix

注意利用了zip()的乙個特性,只返回包含元素個數最短的物件。

這裡比較的是最小字典序字串和最大字典序字串。

若有公共字首,則在這兩個之間一定包含著公共字首。比作字典中的單詞理解就好了。

**如下:

# min 和 max 對字串排序是按字典序排序

deflongestcommonprefix

(strs):if

not strs:

return

'' s1, s2 =

min(strs)

,max

(strs)

for i, c in

enumerate

(s1)

:if c != s2[i]

:return s1[

:i]return s1

若對字典樹不太熟悉的,可以先看 用 python 實現乙個字典樹 這篇文章。

def

longestcommonprefix

(strs):if

not strs:

return

''# 構建字典樹

root =

for word in strs:

ifnot word:

# 處理空字串

return

'' node = root

for char in word:

node = node.setdefault(char,

) node[

'#']

='#'

# 結束標誌

res, node =

'', root

while node !=

:# 注意判斷結束條件

iflen

(node)==1

: char,

= node # 字典中只有乙個 key 時,使用解包操作

res += char

node = node[char]

else

:break

return res

最長公共字首

描述 給k個字串,求出他們的最長公共字首 lcp 樣例 在 abcd abef 和 acef 中,lcp 為 a 在 abcdefg abcefg abcefa 中,lcp 為 abc 新知識點 vectorstrs既可以是一維的,也可以是多維的。在這裡講解三維的初始化。vector str str...

最長公共字首

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

最長公共字首

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