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

LeetCode--Implement strStr()

时间:2015-01-12 09:22:13      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:leetcode   kmp   string   

Implement strStr().

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

Update (2014-11-02):

The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String, please click the reload button  to reset your code definition.

KMP算法的应用

class Solution 
{
public:
    int strStr(char *haystack, char *needle) 
    {
        if(haystack == NULL)
            return -1;
        string hs="";
        string ns="";
        int n=0;
        int m=0;
        while(haystack[n] != '\0')
        {
            hs += haystack[n];
            n++;
        }
        if(needle == NULL)
            return -1;
         while(needle[m] != '\0')
        {
            ns += needle[m];
            m++;
        }
        if( m==0 && n==0)
            return 0;
        if(n==0)
            return -1;
        if(m==0)
            return 0;
        if(m>n)
            return -1;
        int* next = new int[m];
        get_next(needle,next,m);
        int i=0,j=0;
        while(i<n && j<m)
        {
            if(j<0 || hs[i] == ns[j])
            {
                i++;
                j++;
            }
            else
                j = next[j];
        }
        if(j==m)
            return i-j;
        else
            return -1;
    }
    void get_next(char* needle, int* next, int n)
    {
        int i=1;
        next[0] = -1;
        while(i<n)
        {
            int k = next[i-1];
            while(k>=0 && needle[k] != needle[i-1])
                k = next[k];
            if(k<0)
                next[i] = 0;
            else
                next[i] = k+1;
            i++;
        }
    }
};


LeetCode--Implement strStr()

标签:leetcode   kmp   string   

原文地址:http://blog.csdn.net/shaya118/article/details/42620443

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