Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Return:
[ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ]
Note: All inputs will be in lower-case
要找到数组中构成元素相同的string,可以先将当前string按照字母排序,存到一个结构中(List或者hashtable中),以后遍历的时候,先看看结构中是否有这个排序后的string存在,如果存在了就找出当时那个string的存储位置,把当前string放进去就好,如果不存在,就新建一个存储位置,放入当前string。
先用List存储排序之后的string,用constains函数判断,只是耗费的时间太长:300多ms:
List<List<String>> result = new ArrayList<List<String>>();
List<String> str = new ArrayList<String>();
for(int i=0;i<strs.length;i++)
{
char[] te = strs[i].toCharArray();
Arrays.sort(te);
String t = String.valueOf(te);
if(str.contains(t))
{
int j = str.indexOf(t);
result.get(j).add(strs[i]);
}
else
{
str.add(t);
List<String> temp = new ArrayList<String>();
temp.add(strs[i]);
result.add(temp);
}
}
return result;
也可以用hashtable来存储排序之后的string,key是排序后的string,value是排序后string相同的index,这样最后去遍历hashtable,把排序后相同的对应index的strs取出来放到一起就好了,时间花费了30多ms:
List<List<String>> result = new ArrayList<List<String>>();
Hashtable<String,List<Integer>> ht = new Hashtable<String,List<Integer>>();
for(int i=0;i<strs.length;i++)
{
char[] te = strs[i].toCharArray();
Arrays.sort(te);
String t = String.valueOf(te);
if(ht.containsKey(t))
{
ht.get(t).add(i);
}
else
{
List<Integer> temp = new ArrayList<Integer>();
temp.add(i);
ht.put(t, temp);
}
}
Iterator<String> it = ht.keySet().iterator();
while(it.hasNext())
{
List<Integer> index = ht.get(it.next());
List<String> temp = new ArrayList<String>();
Iterator<Integer> it1 = index.iterator();
while(it1.hasNext())
{
temp.add(strs[it1.next()]);
}
result.add(temp);
}
return result;