我必须使用递归来实现一个布尔方法。不允许任何for循环。我写的代码证明了给出的正确答案。但是,它还不正确。有什么好的建议吗?谢谢!
public class RecusiveMethod {
public static void main ( String[] args ) {
System.out.println( "True: " + isWordCountsRight( "ccowcow", "cow", 2 ) );
System.out.println( "True: " + isWordCountsRight( "kayakayakaakayak", "kayak", 3 ) );
}
public static boolean isWordCountsRight( String str, String word, int n ) {
if ( n == 0 ) return true;
if ( str.substring( 0, word.length() ).equals( word ) ) {
return isWordCountsRight( str.substring( 1 ), word, n - 1 );
}
return isWordCountsRight( str.substring( 1 ), word, n );
}
}
答案 0 :(得分:1)
您也可以这样做:
public static boolean isWordCountsRight(String str, String word, int n) {
if (n == 0) return true;
int index = str.indexOf(word);
if (index != -1) {
return isWordCountsRight(str.substring(index+1), word, n - 1);
} else {
return false;
}