我正在做codebat作为即将到来的测验,我有练习。我正在使用递归进行递归问题,但我的老师说我应该能够使用其他循环来完成它们。我认为我应该使用for循环,因为它们实现的效果很容易达到相同的结果。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循环已经进入。尝试将大于str.length的值改为小于。 – Ryan
等等,你应该使用循环或递归? Codingbat特别需要递归... –
@SethKitchen我应该使用循环 – user3208915