题目
题目输入
第一行输入字符串 S,第二行输入字符串 L,都只包含英文小写字母。
题目输出
输出 S 串最后一个有效字符在 L 中的位置(首位从 0 开始计算),无有效字符返回 -1。
实例
ace
abcde
输出:4
fgh
abcde
输出:-1
题目解析
题目
题目代码
#include <iostream>
#include <string>
using namespace std;
int StringCmpStr(string S, string L){
int lS = S.size();
int lL = L.size();
if(lS > lL) return -1;
int slowIndex = 0;
int result = -1;
for(int i = 0; i < lL; i++){
if(slowIndex < lS && L[i] == S[slowIndex]){//slowIndex < lS是为了后面使用S[slowIndex]导致数组越界
result = i;
slowIndex++;
}
if(slowIndex == lS){//slowIndex是下标;lS是长度,进入这个条件说明找到了有效子序列
break;
}
}
result = slowIndex == lS ? result : -1;
return result;
}
int main(){
string S, L;
getline(cin, S);
getline(cin, L);
int result = StringCmpStr(S, L);
cout << result <<endl;
return 0;
}