问题
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