diff --git a/problems/1047.删除字符串中的所有相邻重复项.md b/problems/1047.删除字符串中的所有相邻重复项.md index 4aa0e954..7232008a 100644 --- a/problems/1047.删除字符串中的所有相邻重复项.md +++ b/problems/1047.删除字符串中的所有相邻重复项.md @@ -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