给出一个字符串数组S,找到其中所有的乱序字符串(Anagram)。如果一个字符串是乱序字符串,那么他存在一个字母集合相同,但顺序不同的字符串也在S中。
注意事项
所有的字符串都只包含小写字母
对于字符串数组 ["lint","intl","inlt","code"]
返回 ["lint","inlt","intl"]
/*
思路:
先进行排序,然后用hash表记录个数
*/
public class Solution {
//对每个字符串进行排序,然后用hash表记录个数就行
/*public List<String> anagrams(String[] strs) {
// write your code here
List<String> list = new ArrayList<String>();
if(strs == null || strs.length ==0)return list;
Map<String,Integer> map = new HashMap<String,Integer>();
//定义一个新字符串数组作为临时
String[] strs2 = new String[strs.length];
for(int i=0;i< strs.length;i++){
char[] ch = strs[i].toCharArray();//一个个子字符串来存
Arrays.sort(ch);//对一个个字符串排序 sort(strs[i])不行
strs2[i] = String.valueOf(ch);//用新字符串来存排序好的strs[i]
//判断键是否存在
//不存在则加入,设置值为1
if(!map.containsKey(strs2[i])){
map.put(strs2[i],1);
}else{
//存在即相同,设置值加1
map.put(strs2[i],map.get(strs2[i]) + 1);//根据已经存入的键,对应值加1;
}
}
for(int i=0;i<strs.length;i++){
if(map.get(strs2[i]) >1)//值大于1,则为乱序的值
list.add(strs[i]);//list添加strs中元素,不是排序好元素
}
return list;
}