should return true if substr is in str. Return false otherwise

Viewed 35

how can I pass this test case? I wrote this method, while in difficulty.

Implement a contains function that accepts arrays of characters str and substr. The function should return true if substr is in str. Return false otherwise.

Failed test #5 of 31. Input data: xzofvvl

Your answer: false Correct answer: true

public static void main(String[] args) {

    char[] str = {'Q', 'e', 'r', 't', 'y'};
    char[] sub1 = {'e', 'r', 't'};
    char[] sub2 = {' ', ' ', ' ', ' '};
    char[] sub3 = {' ', 'e', 'r', 't', 'y'};


    System.out.println(contains(str, sub2));
}


public static boolean contains(char[] str, char[] substr) {
    int targetIndex = 0;

    if (str.length > substr.length && substr.length > 0) {
        for (int i = 0; i < str.length; i++) {

            if (str[i] == substr[targetIndex]) {
                targetIndex = targetIndex + 1;
                if (targetIndex == substr.length) {
                    return true;
                }
            }

        }
    } else {
        return false;
    }
    return false;
}

I solved this problem, I just needed to return true if subtr comes with a size of 0, thanks to everyone for the help.

1 Answers
public static boolean contains(char[] str, char[] substr) {
    int targetIndex = 0;

    if (str.length > substr.length && substr.length > 0) {
        for (int i = 0; i < str.length; i++) {

            if (str[i] == substr[targetIndex]) {
                targetIndex = targetIndex + 1;
                if (targetIndex == substr.length) {
                    return true;
                }
            } else {
                targetIndex = 0 // you should add this.
            }

        }
    } else {
        return false;
    }
    return false;
}

Without my change, contains("abc", "ac") will return true.

Because for i == 0, targetIndex == 0, 'a' of "abc" == 'a' or "ac";

for i == 1, targetIndex == 1, 'b' of "abc" != 'c' or "ac", but the loop is continue.

Then for i == 2, targetIndex == 1, 'c' of "abc" == 'c' or "ac", and the method return true.

Related