28. Implement strStr()

来源:互联网 发布:淘宝拍卖车辆靠谱吗 编辑:程序博客网 时间:2024/06/05 10:29

Implement strStr().

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


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


class Solution {public:    int strStr(string haystack, string needle) {        return haystack.find(needle);            }};


0 0