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

【LeetCode】Implement strStr()

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

标签:style   c   class   blog   code   java   

 

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()

标签:style   c   class   blog   code   java   

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

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