Liondancer
Liondancer

Reputation: 16469

Custom indexOf without String methods

I created my own indexOf function. I was wondering if anyone could help me come up with a way to make it more efficient. I am practicing for interviews so the catch is that I cannot use any String methods. I believe the runtime of this method is O(n^2) with space of O(n). Correct me if I am wrong.

Also, I want to ensure the program runs safely and correctly, the only test case I can think of it the length comparison.

code:

public static int myIndexOf(char[] str, char[] substr) {
    int len = str.length;
    int sublen = substr.length;
    int count = 0;
            if (sublen > len) {
                return -1;
            }
    for (int i = 0; i < len - sublen + 1; i++) {
        for (int j = 0; j < sublen; j++) {
            if (str[j+i] == substr[j]) {
                count++;
                if (count == sublen) {
                    return i;
                }
            } else {
                count = 0;
                break;
            }
        }
    }
    return -1;
}

Upvotes: 0

Views: 425

Answers (1)

Paul
Paul

Reputation: 3058

Try here for string searching algorithms: http://www-igm.univ-mlv.fr/~lecroq/string/

And here for a way to test your implementation: http://junit.org/

Upvotes: 1

Related Questions