题意:找出一组字符串中所有回文的字符串,即由相同的字符组成的字符串。
思路:用一个HashMap存储,对这组字符串中的所有字符串进行一个排序。其中key值存储的是相同的字符串,而value值存储的对应key值的不同字符串。再定义一个result数组,result数组存储由HashMap返回的相同的字符串。
代码:
public ArrayList<String> anagrams(String[] strs) {
ArrayList<String> result = new ArrayList<>();
if(strs == null || strs.length == 0) return null;
HashMap<String, ArrayList<String>> hm = new HashMap<>();
for(String s : strs){
char []temp = s.tocharArray();
Arrays.sort(temp);
String tempstr = new String(temp);
if(hm.containsKey(tempstr)) {
//这一步的判断非常巧妙
if(hm.get(tempstr).size() == 1){
result.add(hm.get(tempstr).get(0));
}else{
Arraylist<String> tempList = new Arraylist<>();
templist.add(s);
hm.put(tempstr,templist);
}
}
return result;
}