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("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)

}

程序输出:


intermediate value: [[a a b]]

intermediate value: [[aa b b] [aa b]]

last value: [[aa b b] [aa b]]

看起来当函数dfs()返回时,sol被破坏并且它的第一个元素从 [aab] 变为 [aa bb]。


我无法弄清楚我如何声明和使用参数sol和curr.


犯罪嫌疑人X
浏览 146回答 1
1回答

猛跑小猪

从 JimB 和 Ricardo Souza 发表的评论来看,修复是更新时需要的额外附加*sol:*sol&nbsp;=&nbsp;append(*sol,&nbsp;append([]string{},&nbsp;(*curr)...))此代码更改会复制*curr.此外,curr不需要是指针类型。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go