"""
公共前缀
查找字符串数组中的最长公共前缀,
如果不存在公共前缀,返回空字符串。
"""
def is_same(index, char, string_list):
"""
检查字符串列表中的所有字符串是否在给定索引处具有相同的字符。
参数:
index -- 字符串中要检查的索引位置
char -- 要比较的字符
string_list -- 字符串列表
返回:
如果所有字符串在索引处的字符都相同,则返回True;否则返回False。
"""
for item in string_list:
if index >= len(item):
# 如果索引超出任一字符串的长度,说明后续字符无法比较,直接返回False
return False
if char != item[index]:
# 如果任一字符串在索引处的字符与char不同,返回False
return False
return True
def get_max_prefix(string_list):
"""
获取字符串列表中所有字符串的最长公共前缀。
参数:
string_list -- 字符串列表
返回:
最长公共前缀字符串。
"""
if len(string_list) == 0:
# 如果列表为空,直接返回空字符串
return ""
prefix_list = []
base_word = string_list[0]
for index, item in enumerate(base_word):
if is_same(index, item, string_list):
# 如果当前字符是所有字符串在相同索引处的公共字符,添加到前缀列表中
prefix_list.append(item)
else:
# 如果当前字符不是所有字符串的公共字符,结束循环
break
return "".join(prefix_list)
arr = ["flower", "flow", "flight", "flight", "flouoisn"]
print(get_max_prefix(arr))
公共前缀:查找字符串数组中的最长公共前缀
未经允许不得转载:创想未来 » 公共前缀:查找字符串数组中的最长公共前缀

创想未来
评论前必须登录!
注册