首页 > 其他 > 详细

Implement strStr()

时间:2015-05-01 21:09:25      阅读:280      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!