英文:
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]。
我无法弄清楚我在声明和使用参数 sol 和 curr 方面出了什么问题。
英文:
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 < 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("intermediate value:", *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("last value:", 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论