首页 > 其他 > 详细

【LeetCode】Implement strStr()

时间:2014-05-27 23:41:23      阅读:587      评论:0      收藏:0      [点我收藏+]

 

Implement strStr()

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

 

标准KMP算法。可参考下文。

http://blog.csdn.net/yaochunnian/article/details/7059486

核心思想在于求出模式串前缀与后缀中重复部分,将重复信息保存在next数组中。

bubuko.com,布布扣
class Solution 
{
public:
    int getlen(char *str)
    {
        int i;
        for(i = 0; str[i] != \0; i ++)
            ;
        return i;
    }
    void getnext(char *str, int len, int next[])
    {
        int i = 0;
        next[i] = -1;
        int j = -1;

        while(i < len-1)
        {
            if(j==-1 || str[i]==str[j])
            {
                i++;
                j++;
                if(str[i] == str[j])
                    next[i] = next[j];
                else
                    next[i] = j;
            }
            else
                j = next[j];
        }
    }

    char *strStr(char *haystack, char *needle) 
    {
        int hlen = getlen(haystack);
        //cout << "hlen:" << hlen << endl;
        int nlen = getlen(needle);
        //cout << "nlen:" << nlen << endl;

        int *next = new int[nlen];
        getnext(needle, nlen, next);


        int i = 0;
        int j = 0;
        while(i != hlen && j != nlen)
        {
            if(j == -1 || haystack[i] == needle[j])
            {
                i++;
                j++;
            }
            else
            {
                j = next[j];
            }
        }
        if(j == nlen)
            return &haystack[i-nlen];
        else
            return NULL;
    }
};
bubuko.com,布布扣

bubuko.com,布布扣

【LeetCode】Implement strStr(),布布扣,bubuko.com

【LeetCode】Implement strStr()

原文:http://www.cnblogs.com/ganganloveu/p/3753981.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!