您的位置:首页 > 其它

lintcode-medium-Anagrams

2016-03-14 14:37 253 查看
Given an array of strings, return all groups of strings that are anagrams.

Given
["lint", "intl", "inlt", "code"]
, return
["lint", "inlt", "intl"]
.

Given
["ab", "ba", "cd", "dc", "e"]
, return
["ab", "ba", "cd", "dc"]
.

public class Solution {
/**
* @param strs: A list of strings
* @return: A list of strings
*/
public List<String> anagrams(String[] strs) {
// write your code here

List<String> result = new ArrayList<String>();

if(strs == null || strs.length == 0)
return result;

HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();

for(int i = 0; i < strs.length; i++){
String temp = getCount(strs[i]);

if(!map.containsKey(temp))
map.put(temp, new ArrayList<String>());

map.get(temp).add(strs[i]);
}

for(ArrayList<String> value: map.values()){
if(value.size() > 1)
result.addAll(value);
}
return result;
}

public String getCount(String str){
StringBuilder result = new StringBuilder();
int[] count = new int[26];

for(int i = 0; i < str.length(); i++){
count[str.charAt(i) - 'a']++;
}

for(int i = 0; i < 26; i++)
result.append(count[i]);

return result.toString();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: