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

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

Misuse of slices in Go

问题

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

func palindrome(s string) bool {
    for i, j := 0, len(s) - 1; i < j; i, j = i + 1, j - 1 {
        if s[i] != s[j] {
            return false
        }
    }
    return true
}

func dfs(s string, start int, sol *[][]string, curr *[]string) {
    if start == len(s) {
        *sol = append(*sol, *curr)
        fmt.Println("中间值:", *sol)
        return
    }
    
    for i := start + 1; i <= len(s); i++ {
        substr := s[start:i]
        if palindrome(substr) {
            *curr = append(*curr, substr)
            dfs(s, i, sol, curr)
            *curr = (*curr)[:len(*curr) - 1]
        }
    }
}

func main() {
    sol := [][]string{} 
    dfs("aab", 0, &sol, new([]string))
    fmt.Println("最终值:", sol)
}

程序输出:

中间值: [[a a b]]
中间值: [[aa b b] [aa b]]
最终值: [[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:

func palindrome(s string) bool {
    for i, j := 0, len(s) - 1; i &lt; j; i, j = i + 1, j - 1 {
        if s[i] != s[j] {
            return false
        }
    }
    return true
}

func dfs(s string, start int, sol *[][]string, curr *[]string) {
    if start == len(s) {
        *sol = append(*sol, *curr)
        fmt.Println(&quot;intermediate value:&quot;, *sol)
        return
    }
    
    for i := start + 1; i &lt;= len(s); i++ {
        substr := s[start:i]
        if palindrome(substr) {
            *curr = append(*curr, substr)
            dfs(s, i, sol, curr)
            *curr = (*curr)[:len(*curr) - 1]
        }
    }
}

func main() {
    sol := [][]string{} 
    dfs(&quot;aab&quot;, 0, &amp;sol, new([]string))
    fmt.Println(&quot;last value:&quot;, sol)
}

The program outputs:

intermediate value: [[a a b]]
intermediate value: [[aa b b] [aa b]]
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

*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:

*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:

确定