Skip to content

Commit

Permalink
1047.删除字符串中的所有相邻重复项增加Go解法
Browse files Browse the repository at this point in the history
  • Loading branch information
markwang1992 committed Jun 3, 2024
1 parent 55e3828 commit f47eaf1
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions problems/1047.删除字符串中的所有相邻重复项.md
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,33 @@ class Solution:

### Go:

使用栈
```go
func removeDuplicates(s string) string {
stack := make([]rune, 0)
for _, val := range s {
if len(stack) == 0 || val != stack[len(stack)-1] {
stack = append(stack, val)
} else {
stack = stack[:len(stack)-1]
}
}
var res []rune
for len(stack) != 0 { // 将栈中元素放到result字符串汇总
res = append(res, stack[len(stack)-1])
stack = stack[:len(stack)-1]
}
// 此时字符串需要反转一下
l, r := 0, len(res)-1
for l < r {
res[l], res[r] = res[r], res[l]
l++
r--
}
return string(res)
}
```
拿字符串直接作为栈,省去了栈还要转为字符串的操作
```go
func removeDuplicates(s string) string {
var stack []byte
Expand Down

0 comments on commit f47eaf1

Please sign in to comment.