[LeetCode] Anagrams (Java)

Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.


It would be easy to determine whether two strings are anagrams when we sort them. The complexity of sorting a string, which length is n, is $O(nlogn)$. Comparing two strings will cost $O(n)$. We can use a HashMap, in which we use the sorted string as the key, and a list as the value. In the list we will save all strings that have the same key, which is the sorted string. After we have processed all strings, we will check every list to see if the size of it is larger than 1. If it’s larger than 1, it means that there are several strings that are anagrams.



Assuming there are k strings, and the average length of string is n, the complexity will be $O(knlogn)$.