Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
/*
首先搞明白,什么是Anagrams:变换(或颠倒)字母顺序构成的词(或短语)
再就是题目的意思,给出几个字符串,找出其中为Anagrams的字符串
既然是Anagrams,当然至少2个了
Input: ["tea","and","ate","eat","den"]
Output: ["tea","ate","eat"]
*/
public class Solution {
public List<String> anagrams(String[] strs) {
List<String> list = new ArrayList<String>();
Map<String,Integer> map = new HashMap<String,Integer>();
for(int i = 0;i<strs.length;i++) {
char[] bytes = strs[i].toCharArray();
Arrays.sort(bytes);
String sb = new String(bytes);
if(map.containsKey(sb)) {
int index = map.get(sb);
//不等于-1,则index记录的是第一次,则将其加入list
if(index != -1) {
map.put(sb,-1);
list.add(strs[index]);
}
list.add(strs[i]);
} else {
map.put(sb,i);
}
}
//去掉重复反而错list = new ArrayList<String>(new HashSet<String>(list));
return list;
}
}
Have you met this question in a real interview?