Python - K 长度连续字符
给定一个字符串,提取所有 K 个长度的连续字符。
Input : test_str = ‘geekforgeeeksss is bbbest forrr geeks’, K = 3
Output : [‘eee’, ‘sss’, ‘bbb’, ‘rrr’]
Explanation : K length consecutive strings extracted.
Input : test_str = ‘geekforgeeeksss is bbbest forrrr geeks’, K = 4
Output : [‘rrrr’]
Explanation : K length consecutive strings extracted.
方法#1:使用循环
在此,我们维护 counter 来检查元素的连续性,如果它们在单独的元素之前完全等于 K,则返回 number,自身附加 K 次。
Python3
# Python3 code to demonstrate working of
# K length consecutive characters
# Using loop
# initializing string
test_str = 'geekforgeeekssss is bbbbest forrrr geeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 4
res = []
curr, cnt = None, 0
for chr in test_str:
# increment for similar character
if chr == curr:
cnt += 1
else:
curr, cnt = chr, 1
# if count exactly K, element is added
if cnt == K:
res.append(K * chr)
# printing result
print("The K length similar characters : " + str(res))
Python3
# Python3 code to demonstrate working of
# K length consecutive characters
# Using split() + enumerate()
# initializing string
test_str = 'geekforgeeekssss is bbbbest forrrr geeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 4
res = []
for idx, ele in enumerate(test_str):
# creating equi string
substr = ele * K
# checking if equal to actual string
if test_str[idx : idx + K] == substr:
res.append(substr)
# printing result
print("The K length similar characters : " + str(list(set(res))))
输出
The original string is : geekforgeeekssss is bbbbest forrrrrrr geeks
The K length similar characters : ['ssss', 'bbbb', 'rrrr']
方法 #2:使用 split() + enumerate()
在此,我们从每个索引创建子字符串,如果这些子字符串的每个元素相等,则返回结果。
Python3
# Python3 code to demonstrate working of
# K length consecutive characters
# Using split() + enumerate()
# initializing string
test_str = 'geekforgeeekssss is bbbbest forrrr geeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 4
res = []
for idx, ele in enumerate(test_str):
# creating equi string
substr = ele * K
# checking if equal to actual string
if test_str[idx : idx + K] == substr:
res.append(substr)
# printing result
print("The K length similar characters : " + str(list(set(res))))
输出
The original string is : geekforgeeekssss is bbbbest forrrrrrr geeks
The K length similar characters : ['bbbb', 'ssss', 'rrrr']