Skip to content

Commit f47eaf1

Browse files
committed
1047.删除字符串中的所有相邻重复项增加Go解法
1 parent 55e3828 commit f47eaf1

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

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

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,33 @@ class Solution:
241241

242242
### Go:
243243

244+
使用栈
245+
```go
246+
func removeDuplicates(s string) string {
247+
stack := make([]rune, 0)
248+
for _, val := range s {
249+
if len(stack) == 0 || val != stack[len(stack)-1] {
250+
stack = append(stack, val)
251+
} else {
252+
stack = stack[:len(stack)-1]
253+
}
254+
}
255+
var res []rune
256+
for len(stack) != 0 { // 将栈中元素放到result字符串汇总
257+
res = append(res, stack[len(stack)-1])
258+
stack = stack[:len(stack)-1]
259+
}
260+
// 此时字符串需要反转一下
261+
l, r := 0, len(res)-1
262+
for l < r {
263+
res[l], res[r] = res[r], res[l]
264+
l++
265+
r--
266+
}
267+
return string(res)
268+
}
269+
```
270+
拿字符串直接作为栈,省去了栈还要转为字符串的操作
244271
```go
245272
func removeDuplicates(s string) string {
246273
var stack []byte

0 commit comments

Comments
 (0)