【发布时间】:2021-03-23 23:48:15
【问题描述】:
问题是这样的: 给定一个字符串数组,删除前面字符串的变位词的每个字符串,然后按排序顺序返回剩余的数组。
示例 str = ['code', 'doce', 'ecod', 'framer', 'frame']
code 和 doce 是字谜。从数组中删除doc,并在数组中保留第一个出现的代码。
code 和 ecod 是字谜。从数组中删除 ecod 并保留数组中的第一个出现代码。
code 和 framer 不是字谜。将两个字符串都保留在数组中。
framer 和 frame 不是字谜,因为 framer 中有额外的 r。将两个字符串都保留在数组中。
将剩余的字符串按升序排列:['code','frame','framer']。
解决方案代码为:
def checkForAnagrams(word, arr):
# Checking if the word has an anagram in the sliced array.
for x in arr:
if (sorted(word) == sorted(x)):
return True
return False
def funWithAnagrams(text):
limit = len(text)
text.reverse()
# Creating a copy of the list which will be modified,
# and will not affect the array slicing during the loop.
final_text = list(text)
# Looping through the list in reverse since we're eliminating
# the second anagram we find from the original list order.
count = 0
for i in range(0, limit):
if text[i+1:] and checkForAnagrams(text[i], text[i+1:]):
final_text.pop(i - count)
count += 1
return sorted(final_text)
想了解函数funwithanagrams中的text[i+1:]有什么用?
if checkForAnagrams(text[i], text[i+1:]):
会达到相同的输出。
PS-这不是我的代码。我是在网上找到的,很想知道如果删除 text[i+1:] 会如何影响输出?
【问题讨论】:
-
text[i+1:]是列表的所有剩余元素。 -
所以它只是检查列表的其余部分是否有
text[i]的字谜。
标签: python string data-structures anagram