题目:
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
题解:
这道题看所给的字符串数组里面有多少个是同一个变形词变的。这道题同样使用HashMap来帮助存老值和新值,以及帮忙判断是否是变形词。
首先对每个string转换成char array然后排下序,HashMap里面的key存sort后的词,value存原始的词。然后如果这个排好序的词没在HashMap中出现过,那么就把这个sorted word和unsortedword put进HashMap里面。如果一个sorted word是在HashMap里面存在过的,说明这个词肯定是个变形词,除了把这个词加入到返回结果中,还需要把之前第一个存进HashMap里面的value存入result中。
代码如下:
1 public ArrayList anagrams(String[] strs) {
2 ArrayList result=new ArrayList();
3
4 if (strs==null||strs.length==0)
5 return result;
6
7 HashMap> hm = new HashMap>();
8
9 for (String s:strs){
10 char[] temp=s.toCharArray();
11 Arrays.sort(temp);
12 String tempStr=new String(temp);
13
14 if (hm.containsKey(tempStr)){
15 if(hm.get(tempStr).size() == 1)
16 result.add(hm.get(tempStr).get(0));
17 hm.get(tempStr).add(s);
18 result.add(s);
19 }else{
20 ArrayList tempList=new ArrayList();
21 tempList.add(s);
22 hm.put(tempStr, tempList);
23 }
24 }
25 return result;
26 }