最長公共前綴(Python)


編寫一個函數來查找字符串數組中的最長公共前綴。

如果不存在公共前綴,返回空字符串 ""。

示例 1:

輸入: ["flower","flow","flight"]
輸出: "fl"
示例 2:

輸入: ["dog","racecar","car"]
輸出: ""
解釋: 輸入不存在公共前綴。
說明:

所有輸入只包含小寫字母 a-z 。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/longest-common-prefix
我做該題的最開始就想的用第一個字符去匹配所有字符串,發現一個缺陷:

當出現比第一個字符長度還小且匹配的字符串就會報錯,於是把列表長度最小的當判斷點。

class Solution:
def longestCommonPrefix(self, strs):
if len(strs) == 1: # 字符串數組只有一個時返回它本身。
return strs[0]
if len(strs) == "" or strs == []:
return ""
a = len(strs)
n = a-1
while n >= 0: # 從大到小排序
if len(strs[n]) < len(strs[n-1]):
s = strs[n]
strs[n] = strs[n-1]
strs[n-1] = s
n -= 1
b = len(strs[len(strs)-1]) # 獲得長度最小的字符串長度,並保證字符串數組最后一個為最短
j = 0
p = 0
if b <= 0: # 當最小的長度等於0,那么便沒有公共前綴。
return ""
while True:
while strs[0][j] != strs[p+1][j]:
if strs[0][:j] == None :
return ""
else:
return strs[0][:j]
p += 1
if p >= a-1:
j += 1
p = 0
if j == len(strs[p-1]): # 當j等於最短的字符串長度直接返回
return strs[0][:j]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM