Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
思路:暴力破解。也有比较高级的算法,如KMP。KMP的精髓是写一个next函数,当失配的时候,算出后移多少位再匹配,这样可以提升匹配的效率。
#include <iostream>
using namespace std;
class Solution{
public:
//暴力破解
char *strStr(char*haystack,char*needle)
{
if(!*needle) return (char*) haystack;
int len_haystack = strlen(haystack);
int len_needle = strlen(needle);
int j;
for(int i=0;i<=len_haystack - len_needle;i++)
{
for(j=0;j<len_needle;j++)
{
if(needle[j] != haystack[i+j])
{
break;
}
}
if(j == len_needle)
return haystack+i;
}
return NULL;
}
};
void main()
{
char*haystack ="bcd";
char*needle = "bcd";
Solution sol;
char *c = sol.strStr(haystack,needle);
if(c!=NULL)
{
printf("The occurence is %c\n",*c);
}
else
printf("No string include!\n");
}
本文详细介绍了如何使用C++实现字符串匹配算法,包括暴力破解方法及KMP算法的精髓,通过实例展示了如何高效地在主字符串中查找子字符串。
529

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



