mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 12:15:58 +08:00
修改1047.删除字符串中的所有相邻重复项 Java版本
修改1047.删除字符串中的所有相邻重复项 Java版本
This commit is contained in:
@ -122,6 +122,8 @@ public:
|
|||||||
|
|
||||||
|
|
||||||
Java:
|
Java:
|
||||||
|
|
||||||
|
使用 Deque 作为堆栈
|
||||||
```Java
|
```Java
|
||||||
class Solution {
|
class Solution {
|
||||||
public String removeDuplicates(String S) {
|
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:
|
Python:
|
||||||
```python3
|
```python3
|
||||||
|
Reference in New Issue
Block a user