first occurrence of needle in haystack (Implement strStr())

Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

Thoughts:
The naive way is just to iterate through every character in haystack and compare every single character in the substring of haystack with needle. A more efficient way uses the fact that after the (M+N-1)th character in haystack (Assume haystack has M characters and needle has N), we have substrings with length less than N. Then needle cannot occur in any of those substrings so we do not need to look at them.

Code (Java):

public class Solution {
    public String strStr(String haystack, String needle) {
        if(needle.length() == 0)  
            return haystack;
        if(haystack.length() < needle.length())
            return null;
        int diff = haystack.length() - needle.length() + 1;
        for(int i = 0; i < diff; ++i) {
            if(haystack.substring(i).startsWith(needle))
                return haystack.substring(i);
        }
        return null;
    }
}

Code (C++):

class Solution {
public:
    char *strStr(char *haystack, char *needle) {
        if(!*needle)
            return haystack;
        char *p1Adv = haystack;
        char *p2 = needle;
        while(*++p2) {
            p1Adv++;
        }
        char* p1Begin = haystack;
        while(*p1Adv) {
            char* p1 = p1Begin;
            char* p2 = needle;
            while(*p1 && *p2 && *p1 == *p2) {
                p1++;
                p2++;
            }
            if(!*p2)
                return p1Begin;
            p1Begin++;
            p1Adv++;
        }
        return NULL;
    }
};
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

%d bloggers like this: