我这里有笔试,这是说明。
Write a program that prints out groups of words that are anagrams. Anagrams are words that have the same exact letters in them but in a different order. Your output should look something like this:
["demo", "dome", "mode"]
["neon", "none"]
(等)
解决方法如下:
words = ['demo', 'none', 'tied', 'evil', 'dome', 'mode', 'live',
'fowl', 'veil', 'wolf', 'diet', 'vile', 'edit', 'tide',
'flow', 'neon']
result = {}
words.each do |word|
key = word.split('').sort.join
if result.has_key?(key)
result[key].push(word)
else
result[key] = [word]
end
end
result.each do |k, v|
puts "------"
p v
end
我一直试图理解 ruby 代码解决方案,但不能轻易掌握它。我的问题之一是,如果 result
哈希没有键或其中包含任何元素,您如何测试它。 .join
和 .sort
如何处理此代码。
我真的很困惑这一切是如何通过答案的。有哪位大牛能把这段代码逐行解释清楚,通俗易懂,像我这样的初学者都能看懂吗?
最佳答案
我会这样做:
words = ['demo', 'none', 'tied', 'evil', 'dome', 'mode', 'live',
'fowl', 'veil', 'wolf', 'diet', 'vile', 'edit', 'tide',
'flow', 'neon']
words.group_by { |word| word.chars.sort }.values
#=> [["demo","dome","mode"],["none","neon"],["tied","diet","edit","tide"],["evil","live","veil","vile"],["fowl","wolf","flow"]]
关于使用 Split 和 Join 的 Ruby Key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39200885/