Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitf64721e

Browse files
add a solution for 49
1 parent645684b commitf64721e

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

‎src/main/java/com/fishercoder/solutions/_49.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@
99
publicclass_49 {
1010

1111
publicstaticclassSolution1 {
12+
/**
13+
* Time: O(n*k*logk) where n is the # of strings in the given input and k is the maximum length of each string
14+
*/
1215
publicList<List<String>>groupAnagrams(String[]strs) {
1316
Map<String,List<String>>map =newHashMap<>();
1417
for (Stringword :strs) {
@@ -23,4 +26,30 @@ public List<List<String>> groupAnagrams(String[] strs) {
2326
returnnewArrayList<>(map.values());
2427
}
2528
}
29+
30+
publicstaticclassSolution2 {
31+
/**
32+
* This is an improvement to the above solution in terms of time complexity.
33+
* Time: O(n*k) where n is the # of strings in the given input and k is the maximum length of each string
34+
*/
35+
publicList<List<String>>groupAnagrams(String[]strs) {
36+
Map<String,List<String>>map =newHashMap<>();
37+
for (Stringword :strs) {
38+
int[]count =newint[26];
39+
for (charc :word.toCharArray()) {
40+
count[c -'a']++;
41+
}
42+
StringBuildersb =newStringBuilder();
43+
for (intc :count) {
44+
sb.append(c);
45+
sb.append("$");
46+
}
47+
if (!map.containsKey(sb.toString())) {
48+
map.put(sb.toString(),newArrayList<>());
49+
}
50+
map.get(sb.toString()).add(word);
51+
}
52+
returnnewArrayList<>(map.values());
53+
}
54+
}
2655
}

‎src/test/java/com/fishercoder/_49Test.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
importstaticjunit.framework.TestCase.assertEquals;
1414
importstaticjunit.framework.TestCase.assertTrue;
15+
importstaticorg.assertj.core.api.Assertions.assertThat;
1516

1617
publicclass_49Test {
1718
privatestatic_49.Solution1solution1;

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp