赞
踩
题目描述:
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。说明:所有输入均为小写字母。不考虑答案输出的顺序。
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String,List<String>> map = new HashMap<String,List<String>>();
// 遍历每个元素
for(int i = 0 ; i<strs.length ; i++) {
char[] temp1 = strs[i].toCharArray();
Arrays.sort(temp1); // 排序
String temp2 = new String(temp1); // 将字符数组转变为字符串(键)
List<String> temp3 = map.get(temp2);
if(temp3 == null){ // 查看map中是否存在键位temp2的元素,无则创建
temp3 = new ArrayList<String>();
temp3.add(strs[i]);
}else{ // 有则只要将字母异位词添加即可
temp3.add(strs[i]);
}
map.put(temp2,temp3);
}
return new ArrayList<List<String>>(map.values());
}
}
该题是对哈希表的简单应用,首先我们要确定键,按照题意,可以容易知道只有经过排序的字符串才是我们需要的键,然后通过java的hashCode()方法来判断是否为同一个键。如果为同一个键,则加入当前遍历的字符串即可,最后返回map所有的值。
注:字符串的哈希码根据该公式计算 s[0]*31^(n-1) + s[1]*31^(n-2) + … + s[n-1]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。