Finding anagrams for a given word

后端 未结 12 1058
温柔的废话
温柔的废话 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:25

    That depends on how you store your dictionary. If it is a simple array of words, no algorithm will be faster than linear.

    If it is sorted, then here's an approach that may work. I've invented it just now, but I guess its faster than linear approach.

    1. Denote your dictionary as D, current prefix as S. S = 0;
    2. You create frequency map for your word. Lets denote it by F.
    3. Using binary search find pointers to start of each letter in dictionary. Lets denote this array of pointers by P.
    4. For each char c from A to Z, if F[c] == 0, skip it, else
      • S += c;
      • F[c] --;
      • P <- for every character i P[i] = pointer to first word beginning with S+i.
      • Recursively call step 4 till you find a match for your word or till you find that no such match exists.

    This is how I would do it, anyway. There should be a more conventional approach, but this is faster then linear.

提交回复
热议问题