题目
题解
代码
/** * code49 */
import java.util.*;
public class code49 {
public static List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> result = new ArrayList<>();
if (strs.length == 0) {
return result;
}
Map<String, List<String>> map = new HashMap<>();
for (int i = 0; i < strs.length; i++) {
String element = strs[i];
char ch[] = element.toCharArray();
Arrays.sort(ch);
String key = String.valueOf(ch);
List<String> value = map.get(key);
if (value == null) {
value = new ArrayList<String>();
}
value.add(element);
map.put(key, value);
}
// 返回 map 中所有的 value值
for (List<String> value : map.values()) {
result.add(value);
}
return result;
}
public static void main(String[] args) {
String strs[] = { "eat", "tea", "tan", "ate", "nat", "bat" };
List<List<String>> res = groupAnagrams(strs);
System.out.println(res);
}
}