查找组成字符串的重复子字符串(如果存在) [英] Find the repeating substring a string is composed of, if it exists

查看:60
本文介绍了查找组成字符串的重复子字符串(如果存在)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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'

这篇关于查找组成字符串的重复子字符串(如果存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆