首页 > 其他 > 详细

leetcode——Implement strStr() 实现字符串匹配函数(AC)

时间:2017-07-11 12:39:23      阅读:281      评论:0      收藏:0      [点我收藏+]

Implement strStr().

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

这个题考查的是KMP算法。先求特征向量,然后再进行匹配,确实能够大大提高效率。code例如以下:

class Solution {
public:
    char *strStr(char *haystack, char *needle) {
        if(strlen(haystack)==0&&strlen(needle)==0)
            return haystack;
        if(strlen(haystack)==0&&strlen(needle)!=0)
			return NULL;
		if(strlen(needle)==0)
		    return haystack;
		int m=strlen(needle);
        int *N = new int[m];
		N[0]=0;
		int i,j,k;
		for(i=1;i<m;i++)
		{
			k=N[i-1];
			while(k>0 && needle[i]!=needle[k])
			{
				k=N[k-1];
			}
			if(needle[i]==needle[k])
				N[i]=k+1;
			else
				N[i]=0;
		}
		j=0;
		for(i=0;i<strlen(haystack);i++)
		{
			while(j>0 && needle[j]!=haystack[i])
				j=N[j-1];
			if(needle[j]==haystack[i])
				j++;
			if(j==strlen(needle))
				return haystack+i-j+1;
		}
		return NULL;
    }
};


leetcode——Implement strStr() 实现字符串匹配函数(AC)

原文:http://www.cnblogs.com/lytwajue/p/7149918.html

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