我必须使用递归来实现 boolean 方法。不允许任何 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;
}
关于Java boolean 递归方法用于字符串计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35664574/