Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack。
leetcode上面的一道题。就是一个字符串中是否存在子串和给定的另外一个字符串相等。如果相等,返回该子串首字母的索引。不存在就返回-1。
这道题最容易想到的就是暴力求解。即遍历haystack中的元素。如果某个元素和needle的首元素相等,那么接着比较needle的下一个元素。如果needle中的元素完全匹配,则返回。否则继续遍历haystack中的元素和needle首元素比较。相等,则重复上述过程,不等,继续往下走。代码如下:
int strStr(string haystack, string needle) {
int length_h=haystack.size();
int length_n=needle.size();
if(length_n==0)
{
return 0;
}
if(length_h<length_n)
{
return -1;
}
int n=0;
for(int i=0;i<length_h-length_n+1;i++)
{
if(haystack[i]==needle[n])
{
int j=1;
for(;j<length_n;j++)
{
if(haystack[i+j]!=needle[j])
{
break;
}
}
if(j==length_n)
return i;
}
}
return -1;
}这道题最经典的解法应该是KMP算法。
这里有一个关于KMP算法的比较通俗易懂的解释。链接如下:
http://www.cnblogs.com/c-cloud/p/3224788.html。
本文深入探讨了KMP算法的原理与应用,通过实例展示了如何高效地在字符串中查找子串,避免了传统暴力搜索的低效。文章详细解析了KMP的核心思想——构建前缀函数,并提供了具体代码实现,旨在提升读者在字符串处理领域的技能。
250

被折叠的 条评论
为什么被折叠?



