Merge pull request #202 from Powerstot/patch-7

修改1047.删除字符串中的所有相邻重复项 Java版本
This commit is contained in:
Carl Sun
2021-05-21 09:34:20 +08:00
committed by GitHub

View File

@ -122,6 +122,8 @@ public:
Java
使用 Deque 作为堆栈
```Java
class Solution {
public String removeDuplicates(String S) {
@ -144,6 +146,30 @@ class Solution {
}
}
```
拿字符串直接作为栈,省去了栈还要转为字符串的操作。
```Java
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();
}
}
```
Python
```python3