英文:
golang - string permutation - slice bounds out of range
问题
这是这个问题的Go Playground代码。
我正在尝试使用递归编写一个Golang字符串排列。排列函数接受两个参数,一个是空字符串(""
)的前缀,另一个是字符串"abc"
。代码如下:
func main() {
str := "abc"
perm("", str)
}
func perm(prefix string, str string) {
n := len(str)
fmt.Println(n)
if n == 0 {
fmt.Println(prefix)
} else {
for i := 0; i < n; n++ {
perm(prefix+str[i:i+1], str[0:i]+str[(i+1):n])
}
}
}
当我运行这段代码时,我得到了预期的值3,2,1,0。我成功地得到了"abc",但是然后我得到了一个"panic: runtime error: slice bounds out of range"的错误。
它从未显示第二轮的3,2,1,0,所以它甚至没有到达b
的组合。我觉得如果出现错误,应该是在字符串的c
部分,但是由于它甚至没有到达b
部分,我不确定出了什么问题。
英文:
Here is the Go Playground code for this problem.
I am trying to write a golang string permutation using recursion.
The permutation function takes two arguments, prefix which is an empty string (""
) and str
which is "abc
". The code is below
func main() {
str := "abc"
perm("", str)
}
func perm(prefix string, str string) {
n := len(str)
fmt.Println(n)
if n == 0 {
fmt.Println(prefix)
} else {
for i := 0; i < n; n++ {
perm(prefix+str[i:i+1], str[0:i]+str[(i+1):n])
}
}
}
When I run this code, I am shown 3,2,1,0 for the value of n as expected.
I successfully get "abc
" but then I get a "panic: runtime error: slice bounds out of range
" error.
It never shows the second round of 3,2,1,0 so it doesn't even get to the b
combinations. I feel like if an error would occur is when it gets to the c
portion of the string but since it doesn't even get to the b
portion, I am not sure what is wrong.
答案1
得分: 1
简单示例:
for i := 0; i < n; n++ {
^^^
?
将 n
替换为 i
,i
应该从 0
变化到 n-1
。
结果展示。
英文:
Simple:
for i := 0; i < n; n++ {
^^^
?
Replace n
by i
, which is supposed to go from 0
to n-1
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论