Python 中的最長公共字首
假設我們有一個數組中的字串集合。我們必須找到陣列中字串之間的最長公共字首。這裡我們將假定所有字串都是小寫字串。如果不存在公共字首,則返回 “”。
因此,如果一個字串陣列類似於 ["學校", "時間表", "蘇格蘭"],那麼最長公共字首是 “sc”,因為所有這些字串中都存在 “sc”。
要解決此問題,我們將第一個字串作為 curr,現在從陣列中獲取每個字串並逐個字元地讀取它們,並逐個檢查 curr 和所取字串之間的字元。如果它們相同,則進行下一個字元;否則,中斷迴圈,並將 curr 更新為匹配的子字串。
讓我們看看實現以獲得更好的理解
示例(Python)
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if len(strs) == 0: return "" current = strs[0] for i in range(1,len(strs)): temp = "" if len(current) == 0: break for j in range(len(strs[i])): if j<len(current) and current[j] == strs[i][j]: temp+=current[j] else: break current = temp return current input_list = ["school","schedule","scotland"] ob1 = Solution() print(ob1.longestCommonPrefix(input_list))
輸入
["school","schedule","scotland"]
輸出
"sc"
廣告