leetcode 28. Implement strStr()

来源:互联网 发布:faded软件下载 编辑:程序博客网 时间:2024/06/14 00:01

28. Implement strStr()

Implement strStr().

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

Example 1:

Input: haystack = "hello", needle = "ll"Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"Output: -1

有两种方法:

1、普通:截取长字符串的部分出来比较。

2、运用KMP算法,两个指针的移动来处理。

KMP算法请点  http://blog.csdn.net/liqinzhe11/article/details/78562256


class Solution {public:    int strStr(string hay, string nee)     {        //way-1        /*        if (nee.size() > hay.size())            return -1;        if  (nee.size() == 0)            return 0;                for (int i = 0; i <= hay.size() - nee.size(); i++)        {            if (hay.substr(i, nee.size()) == nee)                return i;            }          return -1;         */                //way-2 KMP        string t = hay;        string p = nee;        int i = 0;  //主串位置          int j = 0;  //模式串位置          vector<int> next(p.size() + 1, -1);          buildnext(p, next, p.size());                   int tsize = t.size();  //这个地方size()需要转化,不然后面while循环会突然退出        int psize = p.size();        while (i < tsize && j < psize )        {              if (j == -1 || t[i] == p[j])  // 当j为-1时,要移动的是i,当然j也要归0              {                  i++;                  j++;              }              else// i不需要回溯了 i = i - j + 1;              {                  j = next[j];              }          }          if (j == p.size())              return i - j;          else              return -1;      }    private:    void buildnext(string& s, vector<int>& next, int n)    {    //next[j]的值(也就是k)表示,当P[j] != T[i]时,j指针的下一步移动位置。    int k = -1;    int j = 0;    while(j < n)        {            if(k == -1 || s[j] == s[k])            {                next[++j] = ++k;            }            else            {                k = next[k];            }        }    }      };