Implement strStr()

2017/12/4 posted in  leetcode

class Solution {
public:
    int strStr(string haystack, string needle) {
        int j = 0;  //标记needle的初始位置
        int h = haystack.length(), n = needle.length();
        if (!n) {
            return 0;
        }
        for (int i =0; i<h-n+1; i++) {
            int tmp = i;
            while (tmp<h && j<n && haystack[tmp]==needle[j]) {
                tmp++;
                j++;
            }
            if (j==n) {
                return i;
            }else{
                j=0;
            }
        }
        return -1;
    }
};