查找组成字符串的重复子字符串(如果存在)

编程入门 行业动态 更新时间:2024-10-18 16:47:27
本文介绍了查找组成字符串的重复子字符串(如果存在)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

您将如何在使用所有字符的同时将普通字符串拆分为尽可能多的相同部分.例如

a = "abab"

将返回 "ab",而 with

b="ababc"

它会返回 "ababc",因为它不能使用所有字母分成相同的部分.

解决方案

这与 我如何判断字符串在 Python 中会重复吗? – 不同之处在于该问题只要求确定字符串是否由相同的重复子字符串组成,而不是重复子字符串(如果有)是什么.

公认的(以及迄今为止最佳表现)该问题的答案 可以调整为返回重复字符串(如果有):

def 中继器:i = (s+s)[1:-1].find(s)如果我 == -1:返回别的:返回 s[:i+1]

示例:

>>>中继器('abab')'ab'>>>中继器('ababc')'ababc'>>>中继器('xyz' * 1000000)'xyz'>>>中继器('xyz' * 50 + 'q')'xyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxy

How would you go about splitting a normal string in to as many identical pieces as possible whilst using all characters. For example

a = "abab"

Would return "ab", whereas with

b= "ababc"

It would return "ababc", as it can't be split into identical pieces using all letters.

解决方案

This is very similar, but not identical, to How can I tell if a string repeats itself in Python? – the difference being that that question only asks to determine whether a string is made up of identical repeating substrings, rather than what the repeating substring (if any) is.

The accepted (and by far the best performing) answer to that question can be adapted to return the repeating string if there is one:

def repeater(s): i = (s+s)[1:-1].find(s) if i == -1: return s else: return s[:i+1]

Examples:

>>> repeater('abab') 'ab' >>> repeater('ababc') 'ababc' >>> repeater('xyz' * 1000000) 'xyz' >>> repeater('xyz' * 50 + 'q') 'xyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzq'

更多推荐

查找组成字符串的重复子字符串(如果存在)

本文发布于:2023-11-30 09:32:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649508.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!