2015-11-24 143 views
0

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

+0

我不认为你的for循环已经进入。尝试将大于str.length的值改为小于。 – Ryan

+0

等等,你应该使用循环或递归? Codingbat特别需要递归... –

+0

@SethKitchen我应该使用循环 – user3208915

回答

1

在你for循环当你说

i >= str.length() - 1 

循环从不输入,因为您正在测试i大于允许的长度(不是)。你需要像

i <= str.length() - 1 

i < str.length() 

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

+0

我试过了,它给了我每个测试的这个错误: '异常:java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-1(线数字:4)' – user3208915

+0

然后它是一个空的'String'。你可以用'String.isEmpty()'来测试这个条件(但是显然一个空的'String'不包含子串)。 –

0

一个你错过的是 “无子串重叠” 的细节。这个问题需要一个while循环,而不是for循环,因为索引会增加不同的数量,具体取决于是否匹配。

以下是可执行代码,用于测试strCount方法是否正常工作。

package com.ggl.testing; 

public class StringCount { 

    public static void main(String[] args) { 
     StringCount stringCount = new StringCount(); 
     System.out.println(stringCount.strCount("catcowcat", "cat")); 
     System.out.println(stringCount.strCount("catcowcat", "cow")); 
     System.out.println(stringCount.strCount("catcowcat", "dog")); 
    } 

    public int strCount(String str, String sub) { 
     int count = 0; 
     int length = str.length() - sub.length(); 
     int index = 0; 

     while (index <= length) { 
      int substringLength = index + sub.length(); 
      if (str.substring(index, substringLength).equals(sub)) { 
       count++; 
       index += sub.length(); 
      } else { 
       index++; 
      } 
     } 

     return count; 
    } 

}