20210309 1047. 删除字符串中的所有相邻重复项

题目

https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string/

题解

直接用栈,和栈顶元素相同就pop出去

public String removeDuplicates(String S) {
if (S.length() <= 1) {
return S;
}
Deque<Character> stack = new ArrayDeque<>();
stack.push(S.charAt(0));
for (int i = 1; i < S.length(); i++) {
if (!stack.isEmpty() && (stack.peek() == S.charAt(i))) {
stack.pop();
} else {
stack.push(S.charAt(i));
}
}
return revStack(stack);
}

private String revStack(Deque<Character> stack) {
char[] array = new char[stack.size()];
int len = array.length - 1;
while (!stack.isEmpty()) {
array[len] = stack.pop();
len--;
}
return new String(array);
}

发表评论

邮箱地址不会被公开。 必填项已用*标注