Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
- All inputs will be in lowercase.
- The order of your output does not matter.
Java Solution :
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> groupedAnagrams = new ArrayList<>();
Map<String , List<String>> map = new HashMap<>();
for(String str : strs){
char [] strchars = str.toCharArray();
Arrays.sort(strchars);
String sorted = new String(strchars);
if(!map.containsKey(sorted))
map.put(sorted,new ArrayList<>());
map.get(sorted).add(str);
}
groupedAnagrams.addAll(map.values());
return groupedAnagrams;
}
}
No comments:
Post a Comment