Grouping anagrams [duplicate]

你说的曾经没有我的故事 提交于 2019-12-22 13:48:24

问题


Given array of words, group the anagrams IP:{tar,rat,banana,atr} OP:{[tar,rat,atr],[banana]}

One solution to this question using Hash Table. consider each word, sort it and add as key to hash table if not present. The value for the key would be a list of all anagrams with the same key. I wanted to know about the time complexities, To sort the characters in an array, suppose O(n log n) To store in the hash table it would be O(n), a total of O(n*nlogn).

Is there a better algorithm? with lesser time complexity?


回答1:


For time complexity's sake, you could always use counting sort to sort the individual words, which cost just linear time per word. You can also first count the occurrences of letters then hash the occurrences count instead of the sorted word, which is essentially the same as counting sort minus the rebuild step.

But since the words will typically be short, this might not buy you any practical advantages.



来源:https://stackoverflow.com/questions/17934627/grouping-anagrams

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!