LeetCod 打卡28
实现strStr()
首先,先看一下题目:
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
示例 2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1
说明:当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很
好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。
解决方法:
在做这道题的时候,看到牛客网送的资料是建议使用C或者C++写,然后就使用了C语言写,因为C++不怎么会。
这道题正好是复习kmp算法的好机会,在大二时候学习数据结构的时候,对这个也是似懂非懂的。在经过一段时间的查资料对kmp算法,终于算上了解了这个kmp算法。不重复造轮子给大家推荐一下讲的清晰明了的一个帖子阮一峰的博客和一个视频西安邮电的数据结构
int kmp(char *tstr,char *pstr,int *next)
{
int i=0;
int j=0;
int tlen=strlen(tstr);
int plen=strlen(pstr);
while(i<tlen&&j<plen){
if(j==-1||tstr[i]==pstr[j])
{
j++;
i++;
}
else
j=next[j];
}
if(j==strlen(pstr))
return i-j;
else
return -1;
}
void get_next(char *pstr,int *next)
{
int plen=strlen(pstr);
int i=0;
int j=-1;
next[0]=-1;
while(i<plen-1)
{
if(j==-1||pstr[i]==pstr[j])
next[++i]=++j;
else
j=next[j];
}
}
int strStr(char* haystack, char* needle) {
int nlen=strlen(needle);
if(nlen==0)
return 0;
int next[nlen];
get_next(needle,next);
return kmp(haystack,needle,next);
}
动动您可爱小手关注我: