Finding anagrams for a given word

后端 未结 12 1032
温柔的废话
温柔的废话 2020-12-04 07:43

Two words are anagrams if one of them has exactly same characters as that of the another word.

Example : Anagram & Nagaram are anagrams

12条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-04 08:16

    Example algorithm:

    Open dictionary
    Create empty hashmap H
    For each word in dictionary:
      Create a key that is the word's letters sorted alphabetically (and forced to one case)
      Add the word to the list of words accessed by the hash key in H
    

    To check for all anagrams of a given word:

    Create a key that is the letters of the word, sorted (and forced to one case)
    Look up that key in H
    You now have a list of all anagrams
    

    Relatively fast to build, blazingly fast on look-up.

提交回复
热议问题