Thanks for looking at my problem
I try to code this problem in golang:
Here is Code:
func partition(s string) [][]string {
return helper(0, s, nil, nil)
}
func helper(level int, s string, temp []string, res [][]string ) [][]string {
if level == len(s) {
el := make([]string, len(temp))
copy(el, temp)
res = append(res, temp)
return res
}
for i:= level+1; i<= len(s); i++ {
if valid(s[level:i]) {
fmt.Println(level)
fmt.Println(s[level: i])
temp = append(temp, s[level:i])
res = helper(i, s, temp, res)
fmt.Println("res ",res)
temp = temp[:len(temp)-1]
}
}
return res
}
func valid(s string) bool {
if len(s) == 1 {
return true
}
for i, j := 0, len(s)-1; i<j; i, j = i+1, j-1 {
if s[i] != s[j] {
return false
}
}
return true
}
Here is some console log debugging trace
0
c
1
b
2
c
3
c
res [[c b c c]]
res [[c b c c]]
2
cc
res [[c b cc c] [c b cc]]
res [[c b cc c] [c b cc]]
res [[c b cc c] [c b cc]]
0
cbc
3
c
res [[c b cc c] [c b cc] [cbc c]]
res [[c b cc c] [c b cc] [cbc c]]
Algorithm is basic DFS which temp as intermediate holder to contribute one piece result to final output.
if you try to use test case like βcbccβ, the output is [[βcβ,βbβ,βccβ,βcβ],[βcβ,βbβ,βccβ],[βcbcβ,βcβ]], but expect answer is [[βcβ,βbβ,βcβ,βcβ],[βcβ,βbβ,βccβ],[βcbcβ,βcβ]], you can see that only first slice in slices have different output which βccβ should be βcβ, I think the second one [βcβ,βbβ,βccβ] somehow override the previous existing one. I am not sure about string slice internally, but I believe since string in golang is immutable which is safe-slicing.
Which part is I am missing? Or any better way to handle string slicing in this case.