gpt4 book ai didi

java - Codingbat 将递归循环转换为 for 循环?

转载 作者:行者123 更新时间:2023-12-01 10:51:03 25 4
gpt4 key购买 nike

我正在做codingbat作为我即将进行的测验的练习。我正在使用递归来解决递归问题,但我的老师说我应该能够使用其他循环来解决这些问题。我认为我应该使用 for 循环,因为它们可以轻松实现相同的结果。

但是我在将递归转换为 for 循环时遇到问题。

这就是问题:

Given a string and a non-empty substring sub, compute recursively the number of times that sub appears in the string, without the sub strings overlapping.

strCount("catcowcat", "cat") → 2

strCount("catcowcat", "cow") → 1

strCount("catcowcat", "dog") → 0

这是我尝试使用的代码:

public int strCount(String str, String sub) {
int number = 0;
for (int i = 0; i >= str.length() - 1; i++) {
if (str.substring(i, sub.length()).equals(sub)) {
number += 1;
}
}

return number;
}

当我返回时,一切都返回为 0。

最佳答案

在你的 for 循环中,当你说

i >= str.length() - 1

永远不会进入循环,因为您正在测试 i 是否大于允许的长度(但事实并非如此)。你需要类似的东西

i <= str.length() - 1

i < str.length()

此外,number += 1; 可以写成 number++;

关于java - Codingbat 将递归循环转换为 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33904983/

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