Skip to content

Commit 59918e8

Browse files
committed
First Unique Character in a String: Time Limit Exceeded
1 parent b59b41f commit 59918e8

1 file changed

Lines changed: 58 additions & 0 deletions

File tree

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package leetcode.medium.page1;
2+
3+
import java.util.*;
4+
5+
public class GroupAnagrams {
6+
public List<List<String>> groupAnagrams(String[] strs) {
7+
List<List<String>> res = new ArrayList<>(strs.length);
8+
int count = 0;
9+
10+
int[] flag = new int[strs.length];
11+
12+
for (int i = 0; i < strs.length; i++) {
13+
if (flag[i] == 1) {
14+
continue;
15+
}
16+
List<String> curGroup = new LinkedList<>();
17+
curGroup.add(strs[i]);
18+
19+
Map<Character, Integer> iFeature = new HashMap<>(strs[i].length());
20+
for (int f = 0; f < strs[i].length(); f++) {
21+
iFeature.put(strs[i].charAt(f), iFeature.getOrDefault(strs[i].charAt(f), 0) + 1);
22+
}
23+
24+
for (int j = i + 1; j < strs.length; j++) {
25+
if (strs[i].length() != strs[j].length()) {
26+
continue;
27+
}
28+
29+
boolean sameGroup = true;
30+
Map<Character, Integer> jFeature = new HashMap<>(strs[j].length());
31+
for (int f = 0; f < strs[j].length(); f++) {
32+
jFeature.put(strs[j].charAt(f), jFeature.getOrDefault(strs[j].charAt(f), 0) + 1);
33+
}
34+
35+
if (iFeature.size() != jFeature.size()) {
36+
sameGroup = false;
37+
} else {
38+
for (Map.Entry entry : iFeature.entrySet()) {
39+
if (jFeature.get(entry.getKey()) != entry.getValue()) {
40+
sameGroup = false;
41+
break;
42+
}
43+
}
44+
}
45+
46+
if (sameGroup) {
47+
curGroup.add(strs[j]);
48+
flag[j] = 1;
49+
}
50+
}
51+
52+
res.add(curGroup);
53+
count++;
54+
}
55+
56+
return res;
57+
}
58+
}

0 commit comments

Comments
 (0)