[leetcode]: 28. Implement strStr()

来源:互联网 发布:好听的网络歌曲 推荐 编辑:程序博客网 时间:2024/05/27 14:12

1.题目

Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
手动实现strStr()函数,返回子字符串needle在字符串haystack中第一次出现的位置

2.分析

暂时还没去学习KMP,所以就手动遍历匹配字符串了。

3.代码

class Solution {public:    int strStr(string haystack, string needle) {        if (needle.size()==0)            return 0;        if (haystack.size()<needle.size())            return -1;        for (int i = 0; i <= haystack.size() - needle.size(); i++) {            int j = 0;            while (j<needle.size() && haystack[i + j] == needle[j])                ++j;            if (j == needle.size())                return i;        }        return -1;    }};
原创粉丝点击