Skip to content

Commit 74c47d1

Browse files
add a solution for 1209
1 parent fccda5e commit 74c47d1

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

src/main/java/com/fishercoder/solutions/_1209.java

+29
Original file line numberDiff line numberDiff line change
@@ -43,4 +43,33 @@ public String removeDuplicates(String s, int k) {
4343
return sb.reverse().toString();
4444
}
4545
}
46+
47+
public static class Solution2 {
48+
public String removeDuplicates(String s, int k) {
49+
StringBuilder sb = new StringBuilder();
50+
int dupCount = 0;
51+
for (int i = 0; i < s.length(); i++) {
52+
if (sb.length() != 0 && sb.charAt(sb.length() - 1) == s.charAt(i)) {
53+
dupCount++;
54+
} else {
55+
dupCount = 1;
56+
}
57+
sb.append(s.charAt(i));
58+
if (dupCount == k) {
59+
sb.setLength(sb.length() - k);
60+
if (i + 1 < s.length()) {
61+
dupCount = 0;
62+
for (int j = sb.length() - 1; j >= 0; j--) {
63+
if (sb.charAt(j) == s.charAt(i + 1)) {
64+
dupCount++;
65+
} else {
66+
break;
67+
}
68+
}
69+
}
70+
}
71+
}
72+
return sb.toString();
73+
}
74+
}
4675
}

src/test/java/com/fishercoder/_1209Test.java

+11
Original file line numberDiff line numberDiff line change
@@ -9,25 +9,36 @@
99
public class _1209Test {
1010

1111
private static _1209.Solution1 solution1;
12+
private static _1209.Solution2 solution2;
1213

1314
@BeforeClass
1415
public static void setup() {
1516
solution1 = new _1209.Solution1();
17+
solution2 = new _1209.Solution2();
1618
}
1719

1820
@Test
1921
public void test1() {
2022
assertEquals("abcd", solution1.removeDuplicates("abcd", 2));
23+
assertEquals("abcd", solution2.removeDuplicates("abcd", 2));
2124
}
2225

2326
@Test
2427
public void test2() {
2528
assertEquals("aa", solution1.removeDuplicates("deeedbbcccbdaa", 3));
29+
assertEquals("aa", solution2.removeDuplicates("deeedbbcccbdaa", 3));
2630
}
2731

2832
@Test
2933
public void test3() {
3034
assertEquals("ps", solution1.removeDuplicates("pbbcggttciiippooaais", 2));
35+
assertEquals("ps", solution2.removeDuplicates("pbbcggttciiippooaais", 2));
36+
}
37+
38+
@Test
39+
public void test4() {
40+
assertEquals("ghayqgq", solution1.removeDuplicates("ghanyhhhhhttttttthhyyyyyynnnnnnyqkkkkkkkrrrrrrjjjjjjjryyyyyyfffffffygq", 7));
41+
assertEquals("ghayqgq", solution2.removeDuplicates("ghanyhhhhhttttttthhyyyyyynnnnnnyqkkkkkkkrrrrrrjjjjjjjryyyyyyfffffffygq", 7));
3142
}
3243

3344
}

0 commit comments

Comments
 (0)