You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
class Solution {
public String removeDuplicates(String s, int k) {
Stack<Pair> stack = new Stack<>();
int n = s.length();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
if (stack.isEmpty() || stack.peek().c != c) {
stack.push(new Pair(c, 1));
sb.append(c);
} else {
Pair pair = stack.peek();
pair.count++;
sb.append(c);
if (pair.count == k) {
stack.pop();
sb.delete(sb.length() - k, sb.length());
}
}
}
return sb.toString();
}
}
class Pair {
public char c;
public int count;
public Pair(char c, int count) {
this.c = c;
this.count = count;
}
}
这道题关键是遍历到每个字符,要跟前面的字符匹配并计数,还涉及到消除。所以关键是要想到用栈,用栈保存字符和它出现次数。
The text was updated successfully, but these errors were encountered: