44:Implement strStr()

来源:互联网 发布:视频调色知乎 编辑:程序博客网 时间:2024/06/05 21:51

题目:Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

解题代码如下(本题解法代码的思想及编写参考了网址https://github.com/soulmachine/leetcode#leetcode题解题目):

class Solution {public:        int strStr(string haystack, string needle) {                if (needle.empty()) return 0;                //必须先考虑 needle 不为空的情况                //因为若 needle.size() = 0, 则 N = haystack.size() + 1;                //到时候访问的话会发生越界情况                const int N = haystack.size() - needle.size() + 1;                for (int i = 0; i < N; ++i) {                        int j = i;                        int k = 0;                        while (j < haystack.size() && k < needle.size() && haystack[j] == needle[k])                                ++j, ++k;                        if (k == needle.size())  return i;                }                return -1;        }};
0 0
原创粉丝点击