我必须使用递归来实现布尔方法。不允许任何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 );
    }
}

最佳答案

您也可以这样:

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;
}

08-06 20:13