Skip to content

Commit 4fe9f44

Browse files
author
applewjg
committed
Anagrams
Change-Id: I9a1764ca825de629dce15809f5f9b7458dfd87a1
1 parent 12e004c commit 4fe9f44

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Anagrams.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
Author: King, [email protected]
3+
Date: Dec 25, 2014
4+
Problem: Anagrams
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/anagrams/
7+
Notes:
8+
Given an array of strings, return all groups of strings that are anagrams.
9+
Note: All inputs will be in lower-case.
10+
11+
Solution: Sort the string to see if they're anagrams.
12+
*/
13+
14+
import java.util.Map.Entry;
15+
public class Solution {
16+
public List<String> anagrams(String[] strs) {
17+
ArrayList<String> res = new ArrayList<String>();
18+
HashMap<String, ArrayList<String>> group = new HashMap<String, ArrayList<String>>();
19+
if (strs.length == 0) return res;
20+
for (int i = 0; i < strs.length; ++i) {
21+
char[] tmp = strs[i].toCharArray();
22+
Arrays.sort(tmp);
23+
String s = String.valueOf(tmp);
24+
if(group.containsKey(s))
25+
(group.get(s)).add(strs[i]);
26+
else {
27+
ArrayList<String> t = new ArrayList<String>();
28+
t.add(strs[i]);
29+
group.put(s,t);
30+
}
31+
}
32+
Iterator<Entry<String, ArrayList<String>>> iter = group.entrySet().iterator();
33+
while (iter.hasNext()) {
34+
Map.Entry entry = (Map.Entry) iter.next();
35+
ArrayList<String> val = (ArrayList<String>) entry.getValue();
36+
if (val.size() > 1) res.addAll(val);
37+
}
38+
return res;
39+
}
40+
}

0 commit comments

Comments
 (0)