Implement strStr()

方法一:使用基本的遍历算法

class Solution {
public:
    int strStr(string haystack, string needle) {
        int len1 = haystack.size();
        int len2 = needle.size();
        for(int i=0; i < len1 - len2 + 1; ++i)
        {
            int num = i;
            int j = 0;
            bool flag = true;
            for(; j<needle.size(); ++j, ++num)
            {
                if(haystack[num] != needle[j])
                    flag = false;
            }
            if(flag)
                return i;
        }
        
        return -1;
    }
};

方法二:使用KMP算法

posted @ 2017-04-21 11:03  chengcy  Views(113)  Comments(0)    收藏  举报