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

96 lines
3.7 KiB
Java
Raw Normal View History

2021-03-20 08:57:12 +00:00
> **[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/)
2021-03-19 10:50:39 +00:00
S****
S
1
> abbaca
> ca
使
##
2021-03-20 06:19:50 +00:00
![](https://img-blog.csdnimg.cn/20210320141506967.gif)
2021-03-19 10:50:39 +00:00
2021-05-05 08:37:51 +00:00
****
2021-03-19 10:50:39 +00:00
2021-05-05 08:37:51 +00:00
Java Code:
2021-03-19 10:50:39 +00:00
```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
2021-05-05 08:37:51 +00:00
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;
}
};
```