Algorithm for grouping anagram words

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

    JavaScript version. using hashing.

    Time Complexity: 0(nm) , where n is number of words, m is length of word

    var words = 'cat act mac tac ten cam net'.split(' '),
        hashMap = {};
    
    words.forEach(function(w){
        w = w.split('').sort().join('');
        hashMap[w] = (hashMap[w]|0) + 1;
    });
    
    function print(obj,key){ 
        console.log(key, obj[key]);
    }
    
    Object.keys(hashMap).forEach(print.bind(null,hashMap))
    

提交回复
热议问题