Implement strStr()

Implement strStr().

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


public class Solution {
    public int strStr(String haystack, String needle) {
        //Needle can be a string 
        for (int i = 0; ; i++) {
            for (int j = 0; ; j++) {
                //if we've checked every char of needle and they all fit -> return i
                if (j == needle.length()) return i; 
                //if we're at the end of haystack and still haven't return -> fail 
                if (i + j == haystack.length()) return -1; 
                //important: if the jth char of needle doesn't fit in haystack -> shift 
                if (needle.charAt(j) != haystack.charAt(i+j)) break;
            }
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s