2

http://spark-university.s3.amazonaws.com/berkeley-saas/homework/hw1.pdf

尝试完成此作业的第 3 部分。以下代码似乎不起作用,即对于参数['HeLLo', 'hello'],返回[["hello"], ["HeLLo"]]而不是[["HeLLo", "hello"]]

def combine_anagrams(words)
    #iterate through words, make hashmap with the sorted version
    hash = {}
    words.each do |x|
        hash[x.chars.sort.join.downcase.gsub /\W/, ""] = []
    end

    #iterate through words, access hashmap and append curr to array
    words.each do |x|
        hash[x.chars.sort.join.downcase.gsub /\W/, ""] << x
    end

    hash.values #return array of values
end

任何帮助,将不胜感激。(我是红宝石新手)

4

1 回答 1

1

您可以像这样轻松地做到这一点:

def combine_anagrams(words)
  anagrams={}
      words.each do |word|
        anagrams[word.downcase.split('').sort.join] ||=[]
        anagrams[word.downcase.split('').sort.join] << word 
      end
      anagrams.values
end
于 2013-04-06T20:49:17.320 回答