Leetcode028. Implement strStr()

class Solution {
public:
    int strStr(string haystack, string needle) {
        if(needle.empty())return 0;    //needle empty 
        if(haystack.empty()) return -1;    //haystack empty
        for(int i = 0, j = 0; i+j < haystack.size();) {
            if(haystack[i+j] != needle[j])i++, j = 0;     //no equal   needle index to 0, haystack index move to next.
            else j++;   //equal both move to next
            if(j == needle.size())return i;     //thr first time find substr.
        }
        return -1;
    }
};

 

posted @ 2016-09-17 08:39  zeroArn  阅读(128)  评论(0)    收藏  举报