http://www.lintcode.com/en/problem/anagrams/
Given an array of strings, return all groups of strings that are anagrams.
Example
Given["lint", "intl", "inlt", "code"], return["lint", "inlt", "intl"].
Given["ab", "ba", "cd", "dc", "e"], return["ab", "ba", "cd", "dc"].
Solution 1
Thinking:
- Using a HashTable to store anagrams (Using the smallest string as a Key)
- For example: string
ba‘s key isab, and its value is itself,ba.
- For example: string
- For each string in the input array, calculate its key and store (key, value) into the hashtable with
mpa.get(key).add(value). In this case, group anagrams will store in the fomation like key: [abc], value [abc, acb, bca, cba].
1 | public class Solution { |
Solution 2
Thinking: The key in hashtable for this solution is calculated by getHash()
1 | /** |