Skip to content

Commit

Permalink
Merge pull request youngyangyang04#2572 from markwang1992/1047-remove…
Browse files Browse the repository at this point in the history
…Duplicates

1047.删除字符串中的所有相邻重复项增加Go解法
  • Loading branch information
youngyangyang04 authored Jun 30, 2024
2 parents 7263271 + f47eaf1 commit c53f566
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 c53f566

Please sign in to comment.