2015-11-24 145 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; 
    } 

}