簡體   English   中英

Leetcode 問題 14. 最長公共前綴 (Python)

[英]Leetcode problem 14. Longest Common Prefix (Python)

我試圖解決這個問題(你可以在這里閱讀描述: https://leetcode.com/problems/longest-common-prefix/ )下面是我想出的代碼。 它給出strs列表中第一個字符串的prefix值,並將前綴與列表中的每個字符串進行比較,彈出所有不相等的字符。

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        prefix = strs[0][0]
        for i in range(len(strs)):
            for j in range(len(prefix)):
                if strs[i][j] != prefix[j]:
                    prefix.pop(prefix[j])
        return prefix

但是這段代碼在第一個測試用例中失敗了,其中strs = ["flower","flow","flight"] Expected output is "fl" ,而我的代碼只返回"f"我正在努力尋找問題所在我的解決方案。 也許你能幫忙?

zip並行迭代字符:

strs = ["flower", "flow", "flight"]

n = 0
for chars in zip(*strs):
    if len(set(chars)) > 1:
        break
    n += 1

# length
print(n) # 2

# prefix
print(strs[0][:n]) # fl

與使用itertools.takewhile的單行程序類似的方法:

from itertools import takewhile

prefix = ''.join([x[0] for x in takewhile(lambda x: len(set(x)) == 1, zip(*strs))])

或者,您可以嘗試使用os - commonprefix 中的庫:(自 Python 3.5+ 起可用)


def longestCommonPrefix(self, strs: List[str]) -> str:
        return os.path.commonprefix(strs)


strs = ["flower","flow","flight"]
print(longestCommonPrefix(strs))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM