Implement strStr()

Problem

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Solution

Implementation of indexOf(): O(m * n) solution

public class Solution {
    public int strStr(String haystack, String needle) {
        for (int i = 0; ; i++) {
            for (int j = 0; ; j++) {
                if (j == needle.length()) return i;
                if (i + j == haystack.length()) return -1;
                if (haystack.charAt(i + j) != needle.charAt(j)) break;
            }
        }

        ///No need to return, all cases handled inside for loop
    }
}

Analysis

A very elegant solution
Outside for loop is to check the different starting index of haystack
Inside for loop is to check if each character in needle matches for current index i
If j == needle.length() means all characters are matched
If i + j == haystack.length() means there is no more character to get from haystack
We break as long as haystack.charAt(i + j) != needle.charAt(j) so that i go to next element

results matching ""

    No results matching ""