HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Recursive Contains Method

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
recursivecontainsmethod

Problem

The method below recursively checks if a string contains another string. Example: contains(hello, lo, 0) should return true, while contains(hello, eh, 0) should return false. The method itself works, but I was wondering how it could be made more efficient/generally better.

Method:

public static boolean contains(String word1, String word2, int index)
{   
    if((word1 == null) || (word2 == null)){
        return false; 
    }

    if(index + (word2.length() - 1) >= word1.length()){
        return false; 
    } 

    int count = 0, j = 0;

    for(int i = index; i < (word2.length() + index); i++){ 
        if(word1.charAt(i) == word2.charAt(j)){
            if((i != 0) && (j != 0)){
                if(word1.charAt(i - 1) == word2.charAt(j - 1)){
                    count++;
                }  
            } else {
                count++;
            }
        }
        j++;
    } 

    if(count == word2.length()){
        return true; 
    } 

    return contains(word1, word2, index + 1);
}

Solution

For proper recursive 'style', you shouldn't use a for-loop inside the function. Each pass through the function should perform one test and then set up the next pass. This also frees you from needing to track the index as an argument.

Consider that:

contains("hello", "lo") == 
contains("ello", "lo") == 
contains("llo", "lo") == 
contains("lo", "lo")

Code Snippets

contains("hello", "lo") == 
contains("ello", "lo") == 
contains("llo", "lo") == 
contains("lo", "lo")

Context

StackExchange Code Review Q#155531, answer score: 2

Revisions (0)

No revisions yet.