gpt4 book ai didi

java - CodingBat——递归编码

转载 作者:行者123 更新时间:2023-12-01 22:17:05 26 4
gpt4 key购买 nike

我正在尝试编码 bat 问题repeatFront:

Given a string and an int n, return a string made of the first n characters of the string, followed by the first n-1 characters of the string, and so on. You may assume that n is between 0 and the length of the string, inclusive (i.e. n = 0 and n <= str.length()).

repeatFront("Chocolate", 4) → "ChocChoChC"
repeatFront("Chocolate", 3) → "ChoChC"
repeatFront("Ice Cream", 2) → "IcI"

这是我正在尝试的代码:

public String repeatFront(String str, int n) {
if(n==0) {
return str;
}
sub = str.substring(0,n);
sub = sub+repeatFront(sub,n-1);
return sub;
}

我得到的错误是字符串末尾有一个额外的字符。第一个示例将给出“ChocChoChCC”,第二个示例将给出“ChoChCC”,依此类推。我只是想从概念上知道我做错了什么以及如何解决它。

最佳答案

啊我发现你的问题了。

如果n == 0,则只能返回空字符串。

返回 str 将在调用 repeatFront(Ch, 1)repeatFront(C, 0) 时再次返回额外的最后一个字母> 都返回C

通过将 n==0 的返回值更改为 return ""; 来修复:

if(n==0) {
return "";
}

关于java - CodingBat——递归编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30762992/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com