一、最長公共前綴
編寫一個函數來查找字符串數組中的最長公共前綴。
如果不存在公共前綴,返回空字符串 ""
。
示例 1:
輸入:strs = ["flower","flow","flight"] 輸出:"fl"
示例 2:
輸入:strs = ["dog","racecar","car"] 輸出:"" 解釋:輸入不存在公共前綴。
class Solution(object):def longestCommonPrefix(self, strs):""":type strs: List[str]:rtype: str"""if not strs: # 如果數組為空,返回空字符串return ""# 找到最短字符串的長度min_len = min(len(s) for s in strs)# 逐個字符比較for i in range(min_len):current_char = strs[0][i] # 取第一個字符串的第 i 個字符for s i