LeetCode49 Letter heterotopic word grouping
Title Description
Given an array of strings , Combine words with different letters . Letter heterotopia refers to the same letter , But arrange different strings .
Examples
Input : ["eat", "tea", "tan", "ate", "nat", "bat"]
Output :
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Algorithm analysis
- After ordering , As key, use hashmap Storage
- Traverse hash Of values, Join in ans that will do
Time complexity
\(O(nLlong(L))\)
Java Code
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
HashMap<String,List<String>> map = new HashMap<String,List<String>>();
int n = strs.length;
for(int i = 0; i < n; i++){
char[] c = strs[i].toCharArray();
Arrays.sort(c);
String s = new String(c);
if(!map.containsKey(s)){
map.put(s, new ArrayList<String>());
}
map.get(s).add(strs[i]);
}
List<List<String>> ans = new ArrayList<List<String>>();
for(List<String> t : map.values()){
ans.add(t);
}
return ans;
}
}