判断字符串子序列
给定字符串target和source,判断target是否为source的子序列。你可以认为target和source 中仅包含英文小写字母,字符串source可能会很长,长度~=500,000,而target是个短字符串,长度<=100。字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串,例如,'abc’是’aebycd’的一个子序列,而’ayb’不是。请找出最后一个序列的起始位置。
示例输入:
abc
abcaybec
示例输出:
3
因为aybec中的abc的a在整个字符串的位置索引是3
#include<iostream>
using namespace std;
int main() {
string target, source;
cin >> target;
cin >> source;
int i = target.size() - 1;
int j = source.size() - 1;
int index = 0;
while (i >= 0) { // 逆序逐字符遍历target
index = 0;
while (j >= 0) { // 逆序逐字符遍历souece
if (target[i] == source[j]) {
index = j;
j--;
break;
}
else {
index = j;
j--;
continue;
}
}
i--;
}
cout << index << endl;
}