美文网首页
28. Implement strStr()

28. Implement strStr()

作者: Al73r | 来源:发表于2017-09-28 00:17 被阅读0次

题目

Implement strStr().

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

分析

字符串匹配问题,打算先撸暴力的,然后再考虑kmp算法优化。

实现

class Solution {
public:
    int strStr(string haystack, string needle) {
        if(needle.empty()) return 0;
        int i=0, j=0, start=0;
        while(i<haystack.size()){
            if(haystack[i]==needle[j]){
                i++; j++;
                if(j==needle.size())
                    return i-needle.size();
            }
            else{
                start++;
                i=start;
                j=0;
            }
        }
        return -1;
    }
};

思考

暴力匹配直接过了,看来kmp算法比较高级,不需要完全掌握啊。

相关文章

网友评论

      本文标题:28. Implement strStr()

      本文链接:https://www.haomeiwen.com/subject/iwwpextx.html