找出字符串数组里的变位词
Given an array of strings, return all groups of strings that are anagrams.
Example
Given ["lint", "intl", "inlt", "code"], return["lint", "inlt", "intl"].
Given ["ab", "ba", "cd", "dc", "e"], return ["ab", "ba", "cd", "dc"].
Note
All inputs will be in lower-case
Solution:
public List<String> anagrams(String[] strs) {
List<String> result = new ArrayList<String>();
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
if(strs == null || strs.length <= 1) {
return result;
}
for(int i = 0; i < strs.length; i++) {
String value = strs[i];
String key = getKey(value);
if(!map.containsKey(key)) {
map.put(key, new ArrayList<String>());
}
map.get(key).add(value);
}
for(ArrayList<String> values : map.values()) {
if(values.size() > 1) {
result.addAll(values);
}
}
return result;
}
private String getKey(String value) {
int[] count = new int[26];
for (int i = 0; i < value.length(); i++) {
count[value.charAt(i) - 'a']++;
}
StringBuffer sb = new StringBuffer();
for (int i : count) {
sb.append(i+"");
}
return sb.toString();
}思路:
为每个字符串生成一个key,这个key只跟字符串的内容有关。将key/value对存在hashmap中,两个字符串同一个key意味着两个字符串等价。
先将字符串填充进数组,然后将数组生成一个字符串。数组将字符串里的字符排列顺序隐藏。
本文介绍了一种有效的算法来识别字符串数组中的变位词。通过为每个字符串生成一个唯一键值,该算法能够快速地将所有等价变位词归类到一起。文章提供了完整的Java实现代码,并详细解释了其工作原理。
1285

被折叠的 条评论
为什么被折叠?



