Algorithm for grouping anagram words

前端 未结 14 1548
悲&欢浪女
悲&欢浪女 2020-12-07 23:30

Given a set of words, we need to find the anagram words and display each category alone using the best algorithm.

input:

man car kile arc none like
<         


        
14条回答
  •  孤城傲影
    2020-12-07 23:51

    Just want to add simple python solution in addition to the other useful answers:

    def check_permutation_group(word_list):
        result = {}
    
        for word in word_list:
            hash_arr_for_word = [0] * 128  # assuming standard ascii
    
            for char in word:
                char_int = ord(char)
                hash_arr_for_word[char_int] += 1
    
            hash_for_word = ''.join(str(item) for item in hash_arr_for_word)
    
            if not result.get(hash_for_word, None):
                result[str(hash_for_word)] = [word]
            else:
                result[str(hash_for_word)] += [word]
    
    return list(result.values())
    

提交回复
热议问题