0

I have to use recursion to implement a boolean method. No any for loop is allowed. The code I wrote turns out the right answer as given. However, it is not correct yet. Is there any good suggestion? Thanks!

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 );
    }
}
3
  • What is the expected outcome? Commented Feb 27, 2016 at 1:23
  • Do you expect 2 or 3 in the second case? Match with overlapping or not? Commented Feb 27, 2016 at 1:28
  • note that you never return false - guess that is your problem here Commented Feb 27, 2016 at 1:40

1 Answer 1

1

You could also do it like so:

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

That's without overlapping. You'll get 2 in the second case.
You're right, I got too greedy by trying to save potentially redundant steps. But that's an easy fix, just replace word.length() by 1
Thanks to all your suggestions!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.