【最长公共后缀】Python 实现

360影视 动漫周边 2025-05-06 14:34 7

摘要:def longest_common_suffix(strs):if not strs:return "@Zero"common_suffix = strs[0]for s in strs[1:]:i = len(common_suffix) - 1j = l

def longest_common_suffix(strs):if not strs:return "@Zero"common_suffix = strs[0]for s in strs[1:]:i = len(common_suffix) - 1j = len(s) - 1temp_suffix = while i >= 0 and j >= 0 and common_suffix[i] == s[j]:temp_suffix.append(common_suffix[i])i -= 1j -= 1common_suffix = ''.join(reversed(temp_suffix))if not common_suffix:return "@Zero"return common_suffix if common_suffix else "@Zero"# 处理输入input_str = input.strip# 尝试解析输入为列表try:# 假设输入是类似 ["abc", "bbc", "c"] 的形式if input_str.startswith('[') and input_str.endswith(']'):input_str = input_str[1:-1]# 分割字符串,去除可能的引号和空格strs = [s.strip(' "\'') for s in input_str.split(',')]except:strs = # 调用函数并输出结果print(longest_common_suffix(strs))

来源:小乐课堂

相关推荐