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);  
    }
};

 

你可能感兴趣的:(Implement strStr())