iT邦幫忙

0

leetcode with python:14. Longest Common Prefix

  • 分享至 

  • xImage
  •  

題目:

Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".

給定一個字串陣列,求出他們的 longest common prefix string ,即從前面開始,最長的共同字串
ex:strs = ["flower","flow","flight"] ==> longest common prefix string:"fl"

我的想法是以第一個字串為基礎從頭開始逐字比較,當確定每個詞條的相同位置都是該值時,記錄到欲回傳的字串
一有不同便回傳當下紀錄的common prefix string

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        ans=""
        for i in range(len(strs[0])):
            for j in strs:
                if i >len(j)-1:
                    return ans
                if strs[0][i]!=j[i]:
                    return ans
            ans=ans+strs[0][i]
        return ans

注意:對比時可能會對到超出其他字串的長度,避免out of range,我們需要再加個判斷式,一旦超出就回傳
最後執行時間37ms(faster than 86.47%)

那我們下題見


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言