Home > Back-end >  Misuse of slices in Go
Misuse of slices in Go

Time:01-08

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.

CodePudding user response:

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.

  •  Tags:  
  • Related