Algorithm for grouping anagram words

前端 未结 14 1520
悲&欢浪女
悲&欢浪女 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:07

    I wouldn't use hashing since it adds additional complexity for look-up and adds. Hashing, sorting and multiplications are all going to be slower than a simple array-based histogram solution with tracking uniques. Worst case is O(2n):

    // structured for clarity
    static bool isAnagram(String s1, String s2)
    {
        int[] histogram = new int[256];
    
        int uniques = 0;
    
        // scan first string
        foreach (int c in s1)
        {
            // count occurrence
            int count = ++histogram[c];
    
            // count uniques
            if (count == 1)
            {
                ++uniques;
            }
        }
    
        // scan second string
        foreach (int c in s2)
        {
            // reverse count occurrence
            int count = --histogram[c];
    
            // reverse count uniques
            if (count == 0)
            {
                --uniques;
            }
            else if (count < 0) // trivial reject of longer strings or more occurrences
            {
                return false;
            }
        }
    
        // final histogram unique count should be 0
        return (uniques == 0);
    }
    

提交回复
热议问题