Thursday, April 24, 2014

[LeetCode] Implement strStr()

Problem Statement (link)
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
Analysis:
No specific algorithm needed for this problem. We simply traverse the two strings and compare each char. The time complexity is O(n*m), where n and m are the lengths of string needle and string haystack, respectively.

Code:
class Solution {
public:
    char *strStr(char *haystack, char *needle) {
        char *st=haystack;
        char *pt1=haystack;
        char *pt2=needle;

        while(*pt1!=NULL && *pt2!=NULL) {
            if (*pt1==*pt2) {
                pt1++; pt2++;
                continue;
            }
            st++;
            pt1=st;
            pt2=needle;
        }
        return *pt2==NULL ? st:NULL;
    }
};

No comments:

Post a Comment