思路:这道题让我们群组给定字符串集中所有的错位词,所谓的错位词就是两个字符串中字母出现的次数都一样,只是位置不同,比如abc,bac, cba等它们就互为错位词,那么我们如何判断两者是否是错位词呢,我们发现如果把错位词的字符顺序重新排列,那么会得到相同的结果,所以重新排序是判断是否互为错位词的方法,由于错位词重新排序后都会得到相同的字符串,我们以此作为key,将所有错位词都保存到map中,然后扫描map即可。
参考:http://www.cnblogs.com/grandyang/p/4385822.html
代码:
public class GroupAnagrams49 {
public static void main(String[] args) {
String[] str ={"eat", "tea", "tan", "ate", "nat", "bat"};
System.out.println(groupAnagrams(str));
}
public static List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> ls = new ArrayList<>();
Map<String, List<String>> map = new HashMap<>();
for (int i = 0; i < strs.length; i++) {
char[] ch = strs[i].toCharArray();
Arrays.sort(ch);
String s = new String(ch);
if (map.containsKey(s))
map.get(s).add(strs[i]);
else {
List<String> list = new ArrayList<String>();
list.add(strs[i]);
map.put(s, list);
}
}
Set<String> keySet = map.keySet();
for(String s : keySet)
ls.add(map.get(s));
return ls;
}
}
输出: