查找子字符串在字符串中连续出现的最多次数

2024-07-08 08:36:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个很长的字符串,我不仅试图找出那些字符的子字符串是否存在于较大的字符串中,我还试图找出连续实例的最长运行时间。你知道吗

例如。。。在下面的代码片段中,我发现我可以使用“count”来查看子字符串b在a中出现的次数,结果是5。然而,我要确定的是最长的连续运行,也就是3(其中“abc”出现在中间的背靠背)。我很难理解这个逻辑。如有任何建议,将不胜感激。你知道吗

a = "abcxyzabcabcabcxyzabcxyz"

b = "abc"

total = a.count(b)

print(total)

Tags: 实例字符串代码count时间逻辑字符次数
3条回答

使用while循环应该相当简单:

def func(a, b): 
    n = 1 
    while b*n in a: 
        n += 1 
    return n - 1 

用适当的索引继续调用a.index上的b。如果索引是子集的开始,则处于相同的运行中。否则,开始新的运行:

def longest_run(string, pattern):
    longest = 0
    current = 0
    start = 0
    while True:
        try:
            ind = string.index(pattern, start)
            if ind == start:
                current += 1
            else:
                if current > longest:
                    longest = current
                current = 1
            start += len(pattern)
        except ValueError:
            return longest

一种可能且简单的解决方案是使用python index函数来标识子字符串的最近索引。在那里,您可以继续向前搜索子字符串,直到找到不再出现的点,然后再次调用index以向前跳过。你知道吗

示例:

a = "abcxyzabcabcabcxyzabcxyz"
b = "abc"

curr_index = a.index(b)
longest_count = 0
current_count = 0

while curr_index < len(a):
    if a[curr_index : curr_index + len(b)] == b:
        curr_index += len(b)
        current_count += 1
    else:
        if longest_count < current_count:
            longest_count = current_count
        try:
            curr_index = a.index(b, curr_index)
        except ValueError:
            # Substring no longer found in string slice
            break
        current_count = 0

if longest_count < current_count:
    longest_count = current_count

print(longest_count)

它只返回最长的重复计数,但不返回开始的位置。然而,添加这些功能是微不足道的。你知道吗

相关问题 更多 >

    热门问题