我这里有一个方法,它接受一个字符串数组,并将彼此不同的字符串分组在一起,每个组形成主数组的子数组anagram_groups
array.
输出很好,但我觉得我的代码可能过于复杂。如果不将事物重构为更多方法,如何简化我的逻辑和/或语法?
def combine_anagrams(words)
anagram_groups = []
# For each word in array argument
words.each do |word|
# Tracking variable for the word
word_added = false
anagram_groups.each do |group|
# Check if word already exists (prevents duplicates)
if group.include? word
word_added = true
# Add word to group if it is an anagram of the first string in the group
elsif word.downcase.chars.sort == group[0].downcase.chars.sort
group << word
word_added = true
end
end
# If word was not an anagram of anything, create new group (subarray)
unless word_added
anagram_groups << [word]
word_added = true
end
end
return anagram_groups
end
这是用于测试的单词数组:
test_words = ['cars', 'for', 'potatoes', 'racs', 'four', 'scar', 'creams', 'scream']
test_words.group_by{|w| w.each_char.sort}.values
会给
[
["cars", "racs", "scar"],
["for"],
["potatoes"],
["four"],
["creams", "scream"]
]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)