在Go语言中滥用切片的问题

huangapple go评论112阅读模式
英文:

Misuse of slices in Go

问题

我正在编写一些代码来查找字符串中的所有回文串:

  1. func palindrome(s string) bool {
  2. for i, j := 0, len(s) - 1; i < j; i, j = i + 1, j - 1 {
  3. if s[i] != s[j] {
  4. return false
  5. }
  6. }
  7. return true
  8. }
  9. func dfs(s string, start int, sol *[][]string, curr *[]string) {
  10. if start == len(s) {
  11. *sol = append(*sol, *curr)
  12. fmt.Println("中间值:", *sol)
  13. return
  14. }
  15. for i := start + 1; i <= len(s); i++ {
  16. substr := s[start:i]
  17. if palindrome(substr) {
  18. *curr = append(*curr, substr)
  19. dfs(s, i, sol, curr)
  20. *curr = (*curr)[:len(*curr) - 1]
  21. }
  22. }
  23. }
  24. func main() {
  25. sol := [][]string{}
  26. dfs("aab", 0, &sol, new([]string))
  27. fmt.Println("最终值:", sol)
  28. }

程序输出:

  1. 中间值: [[a a b]]
  2. 中间值: [[aa b b] [aa b]]
  3. 最终值: [[aa b b] [aa b]]

看起来当函数 dfs() 返回时,sol 被破坏了,它的第一个元素从 [a a b] 变成了 [aa b b]。

我无法弄清楚我在声明和使用参数 solcurr 方面出了什么问题。

英文:

I'm working on some code to find all palindromes from a string:

  1. func palindrome(s string) bool {
  2. for i, j := 0, len(s) - 1; i &lt; j; i, j = i + 1, j - 1 {
  3. if s[i] != s[j] {
  4. return false
  5. }
  6. }
  7. return true
  8. }
  9. func dfs(s string, start int, sol *[][]string, curr *[]string) {
  10. if start == len(s) {
  11. *sol = append(*sol, *curr)
  12. fmt.Println(&quot;intermediate value:&quot;, *sol)
  13. return
  14. }
  15. for i := start + 1; i &lt;= len(s); i++ {
  16. substr := s[start:i]
  17. if palindrome(substr) {
  18. *curr = append(*curr, substr)
  19. dfs(s, i, sol, curr)
  20. *curr = (*curr)[:len(*curr) - 1]
  21. }
  22. }
  23. }
  24. func main() {
  25. sol := [][]string{}
  26. dfs(&quot;aab&quot;, 0, &amp;sol, new([]string))
  27. fmt.Println(&quot;last value:&quot;, sol)
  28. }

The program outputs:

  1. intermediate value: [[a a b]]
  2. intermediate value: [[aa b b] [aa b]]
  3. last value: [[aa b b] [aa b]]

Looks like when function dfs() returns, sol gets corrupted and its first element changes from [a a b] to [aa b b].

I can't figure out what's wrong with how I declare and use parameters sol and curr.

答案1

得分: 1

根据JimB和Ricardo Souza发布的评论,修复方法是在更新*sol时需要额外添加一个append

  1. *sol = append(*sol, append([]string{}, (*curr)...))

这段代码的改动会复制*curr的内容。

另外,curr不需要是指针类型。

英文:

From the comments posted by JimB and Ricardo Souza, the fix is an extra append needed when updating *sol:

  1. *sol = append(*sol, append([]string{}, (*curr)...))

This code change makes a copy of the contents of *curr.

Also, curr doesn't need to be a pointer type.

huangapple
  • 本文由 发表于 2022年1月6日 07:04:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/70600630.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定