题目很简单,有两个字符串A,B,如果B在A中,输出在A中起始地位置。
我们这里先用穷举法:
int index(const string& A,const string& B){
if(A.empty() || B.empty())
return -1;
int len_a = A.length();
int len_b = B.length();
int i=0,j=0;
while(i < len_a && j < len_b){
if(A[i] == B[j]){
i ++;
j ++;
}else{
i = i-j+1; //i退回到上一次匹配首位的下一位
j=0;
}
}
if(j >= len_b){
return i-len_b;
}else
return -1;
}
是的,接下来出场的应该就是KMP了,至于KMP的讲解,《算法》和《大话数据结构》都有详细的说明,很容易懂,这里就不赘述了~~
待续…………..