暴力匹配:
class Solution {
public:
int strStr(string haystack, string needle) {
int m = haystack.size(), n = needle.size();
for (int i = 0; i <= m - n; i++) {
int j = 0;
for (; j < n; j++) {
if (haystack[i + j] != needle[j]) {
break;
}
}
if (j == n) {
return i;
}
}
return -1;
}
};
暴力解二:(这个解有问题,欢迎各位批评指正)
class Solution {
public:
int strStr(string haystack, string needle) {
int l1=haystack.size();
int l2=needle.size();
if(!l1) return 0;
if(l1<l2) return -1;
for(int i=0;i<=l1-l2;i++)
{
int j=i;
for(;j<i+l2;j++)
{
if(haystack[j]!=needle[j])
break;
}
if(j==i+l2-1)
return j;
}
return -1;
}
};