Java boolean 递归方法用于字符串计数

标签 java recursion

我必须使用递归来实现 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/

相关文章:

java - 可以在 Spring 中注入(inject)带参数的方法吗?

java - 谁负责对象转换?

java - OpenGL ES 1.x 中的动画

c++ - 将基数 10 转换为 12,递归添加字母字符时遇到问题

java - 连接卡在 CLOSE_WAIT 状态

java - 在 Struts2 RESTful 插件 POST 请求中返回响应

python - 递归查找最小值(无内置或循环)

javascript - 对象数组中的递归循环

database - 高效持久的递归数据结构

recursion - 如何多次做到这个长度≤1?