Python – 字符串中没有 K 的最长连续性
给定一个字符串,找到最长连续的长度,其中没有出现 K。
Input : test_str = ‘geeksforgeeks is best for geeks’, K = ‘e’
Output : 9
Explanation : from s in best to e in geeks, 9th letter is “e”.
Input : test_str = ‘geeksforgeeks’, K = ‘e’
Output : 7
Explanation : from k to e, 7th letter is e, longest run.
方法#1:使用循环
我们分两步执行此操作,第一步我们迭代所有元素以获得 K 的索引,然后在下一步中找到连续字符之间的最大差异。
Python3
# Python3 code to demonstrate working of
# Longest Consecution without K in String
# Using loop
# initializing string
test_str = 'geeksforgeeks is best for geeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 'e'
# getting all indices
indxs = []
for idx, ele in enumerate(test_str):
if ele == 'e':
indxs.append(idx)
# getting difference
diffs = []
for idx in range(len(indxs) - 1):
diffs.append(indxs[idx + 1] - indxs[idx])
# getting max diff using max()
res = max(diffs)
# printing result
print("Longest run : " + str(res))
Python3
# Python3 code to demonstrate working of
# Longest Consecution without K in String
# Using filter() + lambda + zip() + list comprehension + max()
# initializing string
test_str = 'geeksforgeeks is best for geeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 'e'
# getting all indices using filter + lambda
indxs = list(filter(lambda ele: test_str[ele] == 'e', range(len(test_str))))
# getting difference using zip()
# negative index, for getting successive elements
diffs = [j - i for i, j in zip(indxs[: -1], indxs[1 :])]
# getting max diff
res = max(diffs)
# printing result
print("Longest run : " + str(res))
输出
The original string is : geeksforgeeks is best for geeks
Longest run : 9
方法 #2:使用 filter() + lambda + zip() + 列表理解 + max()
在此,我们使用 filter() + lambda 和 zip() + 列表推导获取 K 元素的索引,用于获取索引之间的差异。发布后, max() 用于提取最大差异。
Python3
# Python3 code to demonstrate working of
# Longest Consecution without K in String
# Using filter() + lambda + zip() + list comprehension + max()
# initializing string
test_str = 'geeksforgeeks is best for geeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 'e'
# getting all indices using filter + lambda
indxs = list(filter(lambda ele: test_str[ele] == 'e', range(len(test_str))))
# getting difference using zip()
# negative index, for getting successive elements
diffs = [j - i for i, j in zip(indxs[: -1], indxs[1 :])]
# getting max diff
res = max(diffs)
# printing result
print("Longest run : " + str(res))
输出
The original string is : geeksforgeeks is best for geeks
Longest run : 9