Python – K 的最长子串长度
给定一个字符串和一个字符K,求 K 的最长子串长度。
Input : test_str = ‘abcaaaacbbaa’, K = b
Output : 2
Explanation : b occurs twice, 2 > 1.
Input : test_str = ‘abcaacccbbaa’, K = c
Output : 3
Explanation : Maximum times c occurs is 3.
方法#1:使用循环
这是解决这个问题的暴力方法,在这种情况下,当遇到 K 时,计数器保持直到出现其他字符,并记录计数,这些计数的最大值被保留并作为结果返回。
Python3
# Python3 code to demonstrate working of
# Longest Substring of K
# Using loop
# initializing string
test_str = 'abcaaaacbbaa'
# printing original String
print("The original string is : " + str(test_str))
# initializing K
K = 'a'
cnt = 0
res = 0
for idx in range(len(test_str)):
# increment counter on checking
if test_str[idx] == K:
cnt += 1
else:
cnt = 0
# retaining max
res = max(res, cnt)
# printing result
print("The Longest Substring Length : " + str(res))
Python3
# Python3 code to demonstrate working of
# Longest Substring of K
# Using findall() + max()
import re
# initializing string
test_str = 'abcaaaacbbaa'
# printing original String
print("The original string is : " + str(test_str))
# initializing K
K = 'a'
# getting all substrings
res = re.findall(r'' + K + '+', test_str)
# getting maximum of substrings Length
res = len(max(res, key = len))
# printing result
print("The Longest Substring Length : " + str(res))
输出
The original string is : abcaaaacbbaa
The Longest Substring Length : 4
方法 #2:使用 findall() + max()
在此,我们使用 findall() 获取 K 的所有可能子字符串,并在其上使用 max() 以获取 len 作为键的最大长度。
Python3
# Python3 code to demonstrate working of
# Longest Substring of K
# Using findall() + max()
import re
# initializing string
test_str = 'abcaaaacbbaa'
# printing original String
print("The original string is : " + str(test_str))
# initializing K
K = 'a'
# getting all substrings
res = re.findall(r'' + K + '+', test_str)
# getting maximum of substrings Length
res = len(max(res, key = len))
# printing result
print("The Longest Substring Length : " + str(res))
输出
The original string is : abcaaaacbbaa
The Longest Substring Length : 4