algorithm-base/animation-simulation/栈和队列/leetcode1047 删除字符串中的所有相邻重复项.md

96 lines
3.7 KiB
Java
Raw Blame History

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
#### [1047. ](https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string/)
S****
S
1
> abbaca
> ca
使
##
![](https://img-blog.csdnimg.cn/20210320141506967.gif)
****
Java Code:
```java
class Solution {
public String removeDuplicates(String S) {
Stack<Character> stack = new Stack<>();
char[] s = S.toCharArray();//先将字符串变成字符数组
//特殊情况
if (S.length() == 0 || S.length() == 1) {
return S;
}
//遍历数组
for (int i= 0; i<S.length(); i++) {
//为空或者和栈顶元素不同时入栈
if(stack.isEmpty() || s[i] != stack.peek()) {
stack.push(s[i]);
}
//相同出栈
else {
stack.pop();
}
}
StringBuilder str = new StringBuilder();
//字符出栈
while (!stack.isEmpty()) {
str.append(stack.pop());
}
//翻转字符并返回
return str.reverse().toString();
}
}
```
set
C++ Code:
```cpp
class Solution {
public:
string removeDuplicates(string S) {
string str;
if (S.empty() || S.size() == 1) {
return S;
}
for (int i = 0; i<S.size(); i++) {
if(str.empty() || S[i] != str.back()) {
str.push_back(S[i]);
}
else {
str.pop_back();
}
}
return str;
}
};
```