从列表值中获取第 K 个索引的最长字母顺序的Python程序
给定一个字符串列表,任务是编写一个Python程序来提取在第 K 个索引处形成最长递增字母顺序的字符串。 K 应该小于所有字符串的最小长度。
Input : test_list = [“gfg”, “is”, “best”, “for”, “geeks”, “and”, “cs”], K = 0
Output : [‘best’, ‘for’, ‘geeks’]
Explanation : Longest subsequence extracted by comparing 0th index. At 0th index, b < f < g. Longest possible consecution. Next being ‘a’ becomes smaller than ‘g’, hence streak breaks.
Input : test_list = [“gfg”, “is”, “geeks”, “and”, “cs”], K = 0
Output : [‘gfg’, ‘is’]
Explanation : Longest subsequence extracted by comparing 0th index.
Input : test_list = [“gfg”, “is”, “geeks”, “and”, “cs”], K = 4
Output : []
Explanation : Smallest lengths in string, is 2 of ‘is’ and ‘cs’. Since K >= min_length, No result.
方法:使用带滑动窗口的循环
在此,我们使用滑动窗口技术不断检查增加的最长子串并不断更新子串序列的最大值,并更新结果列表。
最后相应地打印结果。
示例:
Python3
# Python3 code to demonstrate working of
# Longest Alphabetic order of Kth index
# Using loop with sliding window
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks", "and", "cs"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 1
res = []
curr = test_list[:1]
for idx in range(1, len(test_list)):
# checking for greater element
if test_list[idx][K] <= test_list[idx - 1][K]:
# comparing current with maximum length
if len(curr) > len(res):
res = curr
curr = [test_list[idx]]
else:
curr.append(test_list[idx])
if len(curr) > len(res):
res = curr
# printing result
print("Longest increasing Alphabetic order : " + str(res))
输出:
The original list is : [‘gfg’, ‘is’, ‘best’, ‘for’, ‘geeks’, ‘and’, ‘cs’]
Longest increasing Alphabetic order : [‘geeks’, ‘and’, ‘cs’]