Welcome 歡迎光臨! 愛上網路 - 原本退步是向前

最長的前綴共通字串 LeetCode 14

最長的共通字串:撰寫一個 Function 從一個字串陣列中尋找最長的共通前綴字串,若無共通的前綴,則回傳空白字

Example 1:

Input: ["flower","flow","flight"]

Output: "fl"

Example 2:

Input: ["dog","racecar","car"]

Output: "" Explanation: There is no common prefix among the input strin

 

def longestCommonPrefix(x):
    result = "";                                        #回傳答案 要控制好該值
    compTemp = "";                                      #比對用的陣列
    if(x is not None and len(x) != 0):                  #防呆機制
        result = str(x[0]);                             #既然串列長度 那初始值就取第一個
        for i in range(1,len(x)):                       #比對陣列迴圈-因為我們 已經取串列第一個了 所以從第二個開始 i= 1
            temp = x[i];                                
            for j in range(min(len(result),len(temp))): #用 result(存第一個元素值) 和其他字串比較誰最短 就用此長度 不然怕溢出陣列指標
                if(result[0] != temp[0]):               #第一個指標的字元錯了就回覆空字串
                    return "";
                if(result[j] == temp[j]):               #如果字元相同 
                    compTemp = compTemp + temp[j];      #就將其字元存入暫存 compTemp
            result = compTemp;                          #然後再存到 result 內 , 這樣之後就用result當作 
            compTemp = '';                              #接下都是用 公共前綴 來比較 而不是陣列與陣列比較
    return  result;


instr=["flower","flow","flght"]
print(longestCommonPrefix(instr))
 

 

資料來源

 https://mikeylin.gitbooks.io/leetcode/content/14.html

https://leetcode.wang/leetCode-14-Longest-Common-Prefix.html

[ Python ] 瀏覽次數 : 28 更新日期 : 2024/07/28