class Words:
def prefix(self, words):
common = ""
if words is None:
return ""
# 如果只有一个字符的集合,则直接返回该字符
if len(words) == 1:
return words[0]
min_lenStr = len(words[0])
# 判断字符集里是否存在空字符并判断字符集中最短字符串长度
if words[0] == "":
return ""
for word in words[1:]:
if word == "":
return ""
if len(word) < min_lenStr:
min_lenStr = len(word)
# 匹配最短公共子序列
# 最短字符串作为最外层的循环,然后再依次比较各个字符串的公共前缀
for i in range(min_lenStr):
tar = words[0][i]
for j in range(1, len(words)):
if words[j][i] != tar:
if common:
return common
else:
return ""
common += tar
return common
if __name__ == "__main__":
print("窝窝")
x = Words()
print(x.prefix(["flower", "flow", "flight"]))
网友评论