給定一組字符串,找出它們的最長公共前綴 (Longest Common Prefix)。如果沒有公共前綴,返回空字串 ""
。
範例 1:
Input: strs = ["flower", "flow", "flight"]
Output: "fl"
"fl"
。範例 2:
Input: strs = ["dog", "racecar", "car"]
Output: ""
""
。解決這個問題的關鍵在於如何高效地縮小範圍,找到最長公共前綴。以下列出常見的解法:
思路
實現 (Python)
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs:
return ""
# 初始化 prefix 為第一個字符串
prefix = strs[0]
for s in strs[1:]:
# 縮短 prefix,直到找到公共部分
while not s.startswith(prefix):
prefix = prefix[:-1]
if not prefix:
return ""
return prefix
時間與空間複雜度
思路
實現 (Python)
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs:
return ""
for i in range(len(strs[0])):
char = strs[0][i]
for s in strs[1:]:
# 如果超出長度或字符不匹配,結束掃描
if i >= len(s) or s[i] != char:
return strs[0][:i]
return strs[0]
時間與空間複雜度
思路
實現 (Python)
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs:
return ""
def commonPrefix(left, right):
min_len = min(len(left), len(right))
for i in range(min_len):
if left[i] != right[i]:
return left[:i]
return left[:min_len]
def divideAndConquer(strs, l, r):
if l == r:
return strs[l]
mid = (l + r) // 2
left_prefix = divideAndConquer(strs, l, mid)
right_prefix = divideAndConquer(strs, mid + 1, r)
return commonPrefix(left_prefix, right_prefix)
return divideAndConquer(strs, 0, len(strs) - 1)
時間與空間複雜度
思路
實現 (Python)
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs:
return ""
def isCommonPrefix(length):
prefix = strs[0][:length]
return all(s.startswith(prefix) for s in strs)
min_len = min(len(s) for s in strs)
low, high = 0, min_len
while low < high:
mid = (low + high + 1) // 2
if isCommonPrefix(mid):
low = mid
else:
high = mid - 1
return strs[0][:low]
時間與空間複雜度
最推薦的解法是水平掃描法或垂直掃描法,因為它們簡單直觀且能高效地處理大多數情況。如果數據規模較大,且字符串的長度有較大差異,可以考慮分治法或二分查找法進一步優化。