Algorithm for grouping anagram words

前端 未结 14 1415
悲&欢浪女
悲&欢浪女 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-08 00:11

    Don't bother with a custom hash function at all. Use the normal string hash function on whatever your platform is. The important thing is to make the key for your hash table the idea of a "sorted word" - where the word is sorted by letter, so "car" => "acr". All anagrams will have the same "sorted word".

    Just have a hash from "sorted word" to "list of words for that sorted word". In LINQ this is incredibly easy:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    class FindAnagrams
    {
        static void Main(string[] args)
        {
            var lookup = args.ToLookup(word => SortLetters(word));
    
            foreach (var entry in lookup)
            {
                foreach (var word in entry)
                {
                    Console.Write(word);
                    Console.Write(" ");
                }
                Console.WriteLine();
            }
        }
    
        static string SortLetters(string original)
        {
            char[] letters = original.ToCharArray();
            Array.Sort(letters);
            return new string(letters);
        }
    }
    

    Sample use:

    c:\Users\Jon\Test>FindAnagrams.exe man car kile arc none like
    man
    car arc
    kile like
    none
    

提交回复
热议问题