【问题标题】:Java boolean recursive method for Strings count用于字符串计数的 Java 布尔递归方法
【发布时间】:2016-02-27 09:38:53
【问题描述】:

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

【问题讨论】:

  • 预期结果是什么?
  • 第二种情况下你期望 2 还是 3?是否匹配重叠?
  • 请注意,您永远不会返回 false - 猜猜这是您的问题

标签: java recursion


【解决方案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;
}

【讨论】:

  • 那是没有重叠的。在第二种情况下你会得到 2。
  • 你说得对,我太贪心了,因为我试图保存可能多余的步骤。但这很容易解决,只需将 word.length() 替换为 1
  • 感谢您的所有建议!
猜你喜欢
  • 1970-01-01
  • 2020-06-26
  • 2017-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-12
  • 2017-10-18
  • 1970-01-01
相关资源
最近更新 更多