方法一:Deque作为栈
class Solution {
public String removeDuplicates(String s) {
Deque<Character> stack = new LinkedList<>();
for (char ch : s.toCharArray()) {
if (stack.isEmpty() || ch != stack.peek()) {
stack.push(ch);
} else {
stack.pop();
}
}
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()) {
sb.append(stack.pop());
}
return sb.reverse().toString();
}
}
方法二:StringBuilder作为栈
class Solution {
public String removeDuplicates(String s) {
StringBuilder sb = new StringBuilder();
int top = -1;
for (char ch : s.toCharArray()) {
if (top >= 0 && ch == sb.charAt(top)) {
sb.deleteCharAt(top);
top--;
} else {
sb.append(ch);
top++;
}
}
return sb.toString();
}
}
方法三:数组作为栈
class Solution {
public String removeDuplicates(String s) {
char[] str = s.toCharArray();
int top = -1;
for (char ch : s.toCharArray()) {
if (top == -1 || ch != str[top]) {
str[++top] = ch;
} else {
top--;
}
}
//public static String valueOf(char[] data, int offset, int count)
//offset参数是第一个字符的索引,count参数指定长度
return String.valueOf(str, 0, top + 1);
}
}