最长公共前缀
拟人算法系列文章,以容易理解的方式描述算法,点赞收藏不迷路
class Solution:
def longestCommonPrefix(self, strs: list[str]) -> str:
if not strs:
return ""
min_len = min([len(s) for s in strs])
prefix = ""
for i in range(min_len):
char = strs[0][i]
if all(s[i] == char for s in strs):
prefix += char
else:
break
return prefix
if __name__ == "__main__":
s = Solution()
print(s.longestCommonPrefix(["flower", "flow", "flight"])) # "fl"
首先获得所有字符串的最小长度 min_len,然后一个人逐个拿第一个字符串前 min_len 范围内的每个字符,检查是否所有字符串对应位置的字符都和它一样,如果一样,则追加共同前缀