码迷,mamicode.com
首页 > 其他好文 > 详细

Implement strStr()

时间:2015-05-01 21:10:37      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

class Solution 
{
public:
  char *strStr(char *haystack, char *needle) 
  {
    const int n = strlen(haystack), m = strlen(needle);        
    if (!m)
      return haystack;
    int next[m], i, j;
    next[i = 0] = j = -1;
    //求取next数组
    while (i < m - 1)
    {
      if (j == -1 || needle[i] == needle[j])
        next[++i] = ++j;
      else
        j = next[j];
    }
    //模式匹配
    for (i = j = 0; i < n;)
    {
      if (j == -1 || haystack[i] == needle[j])
        ++i, ++j;
      else
        j = next[j];
      if (j == m)
        return haystack + i - m;
    }
    return NULL;
  }
};

 

Implement strStr()

标签:

原文地址:http://www.cnblogs.com/kkshaq/p/4471070.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!