Skip to content

补充1047用数组模拟栈的go实现 #2930

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 32 additions & 1 deletion problems/1047.删除字符串中的所有相邻重复项.md
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,39 @@ func removeDuplicates(s string) string {
return string(res)
}
```
用数组模拟栈:

~~~go
func removeDuplicates(s string) string {
arr := make([]byte, len(s))
bottom := 0
for i := 0; i < len(s); {
// bottom为0时单独考虑
if bottom == 0 {
arr[bottom] = s[i]
i++
bottom++
continue
}
// bottom指向下一个arr赋值的位置
if s[i] == arr[bottom-1] {
i++
bottom--
} else {
arr[bottom] = s[i]
i++
bottom++
}
}
// 利用切片
return string(arr[:bottom])
}
~~~



拿字符串直接作为栈,省去了栈还要转为字符串的操作

```go
func removeDuplicates(s string) string {
var stack []byte
Expand Down Expand Up @@ -520,4 +552,3 @@ def remove_duplicates(s)
end
```