Py学习  »  Python

如何在Python中找到给定字符的最大重复子串?

Safder • 6 年前 • 1431 次点击  

给定一个字符串‘aabaaab’,我如何找到a的最大子字符串,所以它应该返回‘aaa’。任何帮助都将不胜感激。

def sub_string(s):


   best_run = 0
   current_run = 0

   for char in s:
      if char == 'a'
          current_run += 1
      else:
        current_letter = char

   return(best_run)

我有和上面一样的东西。不知道在哪里能修好。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54115
文章 [ 2 ]  |  最新文章 6 年前
Jason K Lai
Reply   •   1 楼
Jason K Lai    7 年前

a 比得到 max() 根据 len

import re

test_string = 'aabaaab'
split_string_list = re.split( '[^a]', test_string )
longest_string_subset = max( split_string_list, key=len )
print( longest_string_subset )

这个 re 库用于regex '[^a]' 性格。基本上 'aabaaab' 根据regex语句上的任何匹配项被拆分为一个列表,以便 [ 'aa' 'aaa' '' ] 最大值() 语句根据 伦恩 (又名长度)。

您可以阅读有关函数的更多信息,如 re.split() 在文档中: https://docs.python.org/2/library/re.html

Jack Hamby
Reply   •   2 楼
Jack Hamby    7 年前

不是最有效的,而是一个简单的解决方案:

word = "aasfgaaassaasdsddaaaaaafff"

substr_count = 0
substr_counts = []
character = "f"
for i, letter in enumerate(word):
    if (letter == character):
        substr_count += 1
    else:
        substr_counts.append(substr_count)
        substr_count = 0
    if (i == len(word) - 1):
        substr_counts.append(substr_count)

print(max(substr_counts))