题目描述:
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
思路解析:
- 首先判空
- 然后需要创建HashMap来存储排序好的字符串,以及对应有相同字母组成的ArrayList。
- 把每个字符串Arrays.sort以后,再以HashMap的方式加入进去
- 如果HashMap中已经有了这个key了,那么就要把,第一次放进去的value,加入到res中,说明这个是由相同字母组成的值。
代码:
import java.util.*;
public class Solution {
public ArrayList<String> anagrams(String[] strs) {
ArrayList<String> res = new ArrayList<String>();
if(strs==null || strs.length==0){
return res;
}
HashMap<String,ArrayList<String>> hm = new HashMap<String,ArrayList<String>>();
for(String s : strs){
char[] ch = s.toCharArray();
Arrays.sort(ch);
String temp = new String(ch);
if(hm.containsKey(temp)){
if(hm.get(temp).size() == 1)
res.add(hm.get(temp).get(0));
hm.get(temp).add(s);
res.add(s);
}else{
ArrayList<String> templist = new ArrayList<String>();
templist.add(s);
hm.put(temp,templist);
}
}
return res;
}
}