Algorithm for grouping anagram words

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

    I will generate the hasmap based on the sample word and the rest of the alphabets I won't care.

    For example if the word is "car" my hash table will be like this: a,0 b,MAX c,1 d,MAX e,MAX ... .. r,2 . As a result any has greater than 3 will consider as not matching

    (more tuning...) And my comparison method will compare the hash total within the hash calculation itself. It won't continue once it can identify the word is not equal.

    public static HashMap getHashMap(String word) {
            HashMap map = new HashMap();
            String[] chars = word.split("");
            int index = 0;
            for (String c : chars) {
                map.put(c, index);
                index++;
            }
            return map;
        }
    
        public static int alphaHash(String word, int base,
                HashMap map) {
            String[] chars = word.split("");
            int result = 0;
            for (String c : chars) {
                if (c.length() <= 0 || c.equals(null)) {
                    continue;
                }
                int index = 0;
                if (map.containsKey(c)) {
                    index = map.get(c);
                } else {
                    index = Integer.MAX_VALUE;
                }
                result += index;
                if (result > base) {
                    return result;
                }
            }
            return result;
        }
    

    Main method

      HashMap map = getHashMap(sample);
            int sampleHash = alphaHash(sample, Integer.MAX_VALUE, map);
            for (String s : args) {
                    if (sampleHash == alphaHash(s, sampleHash, map)) {
                        System.out.print(s + " ");
                    }
                }
    

提交回复
热议问题