Python如何提取并统计字符串中所有唯一的长度为3的回文
长度为3的回文全量查找实现方案
核心逻辑说明
长度为3的回文固定满足结构:首尾字符一致,中间位为任意字符,不需要复杂的动态规划,基于这个结构可以高效实现需求,同时覆盖所有非连续组合的回文。
完整实现代码
def find_3length_palindromes(s: str): palindromes = set() # 用set自动去重,和示例输出的去重结果匹配 unique_chars = set(s) for edge_char in unique_chars: # 找到当前字符第一次和最后一次出现的位置 first_idx = s.find(edge_char) last_idx = s.rfind(edge_char) # 两个位置之间存在字符,就可以组合出回文 if first_idx < last_idx: # 遍历中间区间的所有字符,拼接回文 for mid_char in set(s[first_idx+1:last_idx]): pal = f"{edge_char}{mid_char}{edge_char}" palindromes.add(pal) # 转成列表方便输出 pal_list = list(palindromes) return len(pal_list), pal_list # 测试示例 if __name__ == "__main__": input_str = "aabca" count, pals = find_3length_palindromes(input_str) print(count) for p in pals: print(p)
运行结果验证
输入aabca时,运行输出和需求示例完全匹配:
3 aba aca aaa
方案优势
- 时间复杂度为O(n),n为字符串长度,不需要遍历所有组合,效率更高
- 自动对重复的回文内容去重,符合示例输出要求
- 既可以拿到总数量,也可以拿到所有具体的回文内容
内容的提问来源于stack exchange,提问作者Pro
相关产品推荐
相关产品推荐

