Implement strStr()

Implement strStr().

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

 

Subscribe to see which companies asked this question

class Solution {
public:
    int strStr(string haystack, string needle) {
        int i,j;  
        for (i = j = 0; haystack[i] && needle[j];) {  
            if (haystack[i] == needle[j]) {  
                ++i;  
                ++j;  
            } else {  
                i = i - j + 1;  
                j = 0;  
            }  
        }  
        return needle[j] ? -1 : (i - j);  
    }
};

 

posted on 2016-01-10 22:50  walkwalkwalk  阅读(112)  评论(0编辑  收藏  举报

导航