|
1 | 1 | class Solution { |
2 | | - private class Letter { |
3 | | - private char c; |
| 2 | + private class Node { |
| 3 | + private char letter; |
4 | 4 | private int count; |
5 | 5 |
|
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; |
21 | 9 | } |
22 | 10 | } |
23 | 11 |
|
24 | 12 | 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 ""; |
27 | 15 | } |
28 | 16 |
|
29 | | - Stack<Letter> st = new Stack<>(); |
| 17 | + StringBuilder sb = new StringBuilder(); |
| 18 | + Stack<Node> st = new Stack<>(); |
30 | 19 |
|
31 | 20 | for (int i = 0; i < s.length(); i++) { |
32 | 21 | char c = s.charAt(i); |
33 | | - int count = 1; |
34 | 22 |
|
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; |
37 | 25 | } else { |
38 | | - Letter l = st.pop(); |
39 | | - l.setCount(l.getCount() + 1); |
40 | | - st.push(l); |
| 26 | + st.push(new Node(c, 1)); |
41 | 27 | } |
42 | 28 |
|
43 | | - if (st.peek().getCount() == k) { |
| 29 | + while (!st.isEmpty() && st.peek().count >= k) { |
44 | 30 | st.pop(); |
45 | 31 | } |
46 | 32 | } |
47 | 33 |
|
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); |
55 | 37 | } |
56 | 38 | } |
57 | 39 |
|
58 | | - return sb.reverse().toString(); |
| 40 | + return sb.toString(); |
59 | 41 | } |
60 | 42 | } |
0 commit comments