题目链接:https://leetcode.com/problems/anagrams/
题目:
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
Note:
- For the return value, each inner list‘s elements must follow the lexicographic order.
- All inputs will be in lower-case.
思路:
将每个字符串的字符排序,将排序后的相同字符串保存在map中,最后要对结果字典序排序。
算法:
-
public List<List<String>> groupAnagrams(String[] strs) {
-
List<List<String>> strss = new ArrayList<List<String>>();
-
HashMap<String, List<String>> maps = new HashMap<String, List<String>>();
-
for (String s : strs) {
-
char c[] = s.toCharArray();
-
Arrays.sort(c);
-
if (!maps.containsKey(String.valueOf(c))) {
-
List<String> l = new ArrayList<String>();
-
l.add(s);
-
maps.put(String.valueOf(c), l);
-
} else {
-
List<String> l = maps.get(String.valueOf(c));
-
l.add(s);
-
maps.put(String.valueOf(c), l);
-
}
-
}
-
Iterator<String> set = maps.keySet().iterator();
-
while (set.hasNext()) {
-
List<String> l = maps.get(set.next());
-
Collections.sort(l);
-
strss.add(l);
-
}
-
return strss;
-
}