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

标签 java for-loop recursion

我正在做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/

相关文章:

java - h :commandButton not working within PrimeFaces p:dataTable

java - 使用 for 循环的 ASCII 字符范围

c++ - 递归创建树

algorithm - 有人可以解释递归插入排序是如何工作的吗?

java - 使用 Javafx 在 ListView 中模仿 CTRL+单击多选

java - NullPointerException 并且无法初始化处理中的草图错误

java - Play Framework 2.0 单元测试

C++ Visual Studio-运算符重载中的空循环会导致调试错误?

bash - 在 Ubuntu 中,如何在 bash for 循环中创建别名?

python - 如何在 pandas 数据框列上最好地执行递归