第14题: 28. Implement strStr()
题目大意:给出两个字符串,求解待匹配串在主串中的位置,如果不是主串的一个子串,则返回-1;如果待匹配串为空的话,则返回0;这与C 中的strsstr()函数一致。
题目分析:一个字符串匹配的求解。第一个印象就是想到了KMP算法,字符串匹配。但是抱着试一试的心理,也用暴力法做了一个求解。
暴力法求解:直接莽,看代码:
class Solution {
public:
int strStr(string haystack, string needle) {
int len1 = haystack.size();
int len2 = needle.size();
if(len2==0) return 0;
int j=0;
for(int i=0;i<len1;i++){
if(haystack[i]==needle[0]){
for(j=1;j<len2;j++){
if(needle[j]!=haystack[i+j]) break;
}
if(j==len2) return i;
}
}
return -1;
}
};
emmmm出乎意料的竟然也通过了,只不过这个时间确实有点真实。至于内存,是因为用了几个额外的变量能存储字符串长度等参数,内存都相差无几。
KMP算法求解:KMP分析过程见另一篇博客,KMP算法和字符串匹配 这里直接上代码
class Solution {
public:
int strStr(string haystack, string needle) {
int len1 = haystack.size();
int len2 = needle.size();
if(len2==0) return 0;
int *next = (int *)malloc(sizeof(int)*len2); // next数组
next[0] = -1;
int j=-1;
for(int i=0;i<len2-1;){ // next数组求解过程
if(j==-1 || needle[i]==needle[j]){
i++;
j++;
next[i] = j;
} else {
j = next[j];
}
}
j = 0;
for(int i=0;i<len1;){ //KMP算法字符串匹配
if(j==-1 || haystack[i]==needle[j]){
i++;
j++;
} else {
j=next[j];
}
if(j==len2) return i-j; // 返回主串中起始匹配位置
}
return -1;
}
};
时间果然快了很多,KMP算法名不虚传。