Skip to content

Commit 83960ed

Browse files
committed
Update 1209_Remove_All_Adjacent_Duplicates_in_String_II.java
1 parent 4166c25 commit 83960ed

File tree

1 file changed

+17
-35
lines changed

1 file changed

+17
-35
lines changed
Lines changed: 17 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,42 @@
11
class Solution {
2-
private class Letter {
3-
private char c;
2+
private class Node {
3+
private char letter;
44
private int count;
55

6-
public Letter(char c, int count) {
7-
this.c = c;
8-
this.count = count;
9-
}
10-
11-
public char getChar() {
12-
return this.c;
13-
}
14-
15-
public int getCount() {
16-
return this.count;
17-
}
18-
19-
private void setCount(int count) {
20-
this.count = count;
6+
public Node(char l, int c) {
7+
letter = l;
8+
count = c;
219
}
2210
}
2311

2412
public String removeDuplicates(String s, int k) {
25-
if (s == null || s.length() < k) {
26-
return s;
13+
if (s == null || s.isEmpty()) {
14+
return "";
2715
}
2816

29-
Stack<Letter> st = new Stack<>();
17+
StringBuilder sb = new StringBuilder();
18+
Stack<Node> st = new Stack<>();
3019

3120
for (int i = 0; i < s.length(); i++) {
3221
char c = s.charAt(i);
33-
int count = 1;
3422

35-
if (st.isEmpty() || st.peek().getChar() != c) {
36-
st.push(new Letter(c, count));
23+
if (!st.isEmpty() && st.peek().letter == c) {
24+
st.peek().count += 1;
3725
} else {
38-
Letter l = st.pop();
39-
l.setCount(l.getCount() + 1);
40-
st.push(l);
26+
st.push(new Node(c, 1));
4127
}
4228

43-
if (st.peek().getCount() == k) {
29+
while (!st.isEmpty() && st.peek().count >= k) {
4430
st.pop();
4531
}
4632
}
4733

48-
StringBuilder sb = new StringBuilder();
49-
50-
while (!st.isEmpty()) {
51-
Letter l = st.pop();
52-
53-
for (int i = 0; i < l.getCount(); i++) {
54-
sb.append(l.getChar());
34+
for (Node n : st) {
35+
for (int i = 0; i < n.count; i++) {
36+
sb.append(n.letter);
5537
}
5638
}
5739

58-
return sb.reverse().toString();
40+
return sb.toString();
5941
}
6042
}

0 commit comments

Comments
 (0)