class Solution {
public String removeDuplicates(String s) {
Stack<Character> stack = new Stack<>();
StringBuilder sb = new StringBuilder();
stack.push(s.charAt(0));
for(int i=1;i<s.length();i++){
if(stack.empty()){
stack.push(s.charAt(i));
}else {
if(stack.peek()==s.charAt(i)){
stack.pop();
}else {
stack.push(s.charAt(i));
}
}
}
while (!stack.empty()){
sb.append(stack.pop());
}
return new String(sb.reverse());
}
}
2.直接拿StringBuffer当栈(参考代码随想录)
class Solution {
public String removeDuplicates(String s) {
// 将 res 当做栈
StringBuffer res = new StringBuffer();
// top为 res 的长度
int top = -1;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
// 当 top > 0,即栈中有字符时,当前字符如果和栈中字符相等,弹出栈顶字符,同时 top--
if (top >= 0 && res.charAt(top) == c) {
res.deleteCharAt(top);
top--;
// 否则,将该字符 入栈,同时top++
} else {
res.append(c);
top++;
}
}
return res.toString();
}
}