Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
Analysis:基本没有会的题,从现在开始把参考人的链接发出来。也算是尊重别人的劳动成果。
Use hashmap to group the anagrams.
1. Pick up a string and sort it.
2. Compare the sorted string with existing keys.
3. If key is there, add the unsorted string to the keys values.
If key is not there, create new hashmap item.
4. Return string groups have size greater than 1.
Solution:
1: HashMap<String,ArrayList<String>> anagrams= new HashMap<String, ArrayList<String>>();
2: ArrayList<String> result=new ArrayList<String>();
3: for(String str: strs)
4: {
5: char[] chars=str.toCharArray();
6: Arrays.sort(chars);
7: String key=new String(chars);
8: if(anagrams.containsKey(key))
9: anagrams.get(key).add(str);
10: else
11: {
12: ArrayList<String> temp=new ArrayList<String>();
13: temp.add(str);
14: anagrams.put(key, temp);
15: }
16: }
17: for(ArrayList<String> group:anagrams.values())
18: {
19: if(group.size()>1)
20: result.addAll(group);
21: }
22: return result;
Reference:https://github.com/ahmetalpbalkan/leetcode-solutions/blob/master/Anagrams.java
没有评论:
发表评论