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

leecode之Implement strStr()

时间:2015-05-29 11:41:11      阅读:89      评论:0      收藏:0      [点我收藏+]

标签:

KMP算法的实现:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int strStr(char* haystack, char* needle) {
    if (haystack == NULL || needle == NULL)
        return -1;
    if (needle[0] == \0)
        return 0;
    int lenPattern = strlen(needle);
    int lenHaystack = strlen(haystack);
    int *shift = (int *)malloc(sizeof(int) * lenPattern);
    int i;
    shift[0] = 0;
    for (i = 1; i < lenPattern; i++){
        if (needle[shift[i - 1]] == needle[i])
            shift[i] = shift[i - 1] + 1;
        else
        {
            if (needle[i] == needle[0])
                shift[i] = 1;
            else
                shift[i] = 0;
        }
    }

    int j = 0;
    for (i = 0; i < lenHaystack;)
    {
        if (haystack[i] == needle[j])
        {
            i++;
            j++;
            if (j == lenPattern)
                return (i - j);
        }
        else
        {
            if (j == 0)
            {
                i++;
            }
            else
            {                
                j = shift[j - 1];
            }
           
        }       
    }
    return -1;
}

int main()
{
    //char *input = "";
    //char *pattern = "";
    char *input = "BBC ABCDAB ABCDABCDABDE";
    char *pattern = "ABCDABD";
    printf("%d\n", strStr(input, pattern));
 
    return 0;
}

 

leecode之Implement strStr()

标签:

原文地址:http://www.cnblogs.com/lakeone/p/4537977.html

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