Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
题意:找出一组字符串中是满足回文构词法(字符串中字符相同,但是顺序不同)的字符串数组。
思路:对字符串数组中的每个字符串按字符排序,通过得到的字符序列来判断两个字符串是否属于回文构词
再用map存储有相同字符串序列的下标即可。
代码:
public class Solution {
public List<String> anagrams(String[] strs) {
List<String> result = new ArrayList<String>();
String[] tmp = Arrays.copyOf(strs, strs.length);
Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();
for(int i = 0 ; i < tmp.length; i++)
{
String str = tmp[i];
char[] cs = str.toCharArray();
Arrays.sort(cs);
str = String.valueOf(cs);
if(!map.containsKey(str))
{
ArrayList<Integer> indexs = new ArrayList<Integer>();
indexs.add(i);
map.put(str, indexs);
}
else {
ArrayList<Integer> indexs = (ArrayList<Integer>)map.get(str);
indexs.add(i);
}
}
for(String str : map.keySet())
{
ArrayList<Integer> indexs = (ArrayList<Integer>)map.get(str);
if(indexs.size() > 1)
{
for(int i : indexs)
{
result.add(strs[i]);
}
}
}
return result;
}
}