标签:
(1)传统的字符串匹配算法:
注意这道题中各种特殊情况的返回值。
传统字符串匹配就是让目标字符串从第一个字母开始逐个匹配源字符串的每一个字符,直到匹配完全。
class Solution {
public:
int strStr(string haystack, string needle) {
int i,j;
i = 0;
j = 0;
if(needle.empty()) return 0;
if(haystack.length() < needle.length())
{
return -1;
}
int lenh,lenn;
lenh = haystack.length();
lenn = needle.length();
while(i !=lenh && j!=lenn)
{
if(haystack[i] == needle[j])
{
++i;
++j;
}
else
{
i = i - j +1;
j = 0;
}
}
return j == lenn ? i - j : -1;
}
};
(2) 使用KMP算法
标签:
原文地址:http://www.cnblogs.com/chdxiaoming/p/4544183.html