■ 题目描述
【字符串子序列II】
给定字符串 target和 source,判断 target是否为 source 的子序列。你可以认为target和 source 中仅包含英文小写字母。
字符串 source 可能会很长(长度~=500,000),而 target是个短字符串(长度<=100)。
字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。
(例如,”abc”是”aebycd”的一个子序列,而”ayb”不是)。
请找出最后一个子序列的起始位置。
输入描述:
第一行为target,短字符串(长度 <=100)
第二行为source,长字符串(长度 ~= 500,000)
输出描述:
最后一个子序列的起始位置,即最后一个子序列首字母的下标
示例1 输入输出示例仅供调试,后台判题数据一般不包含示例
输入
abcabcaybec
说明
这里有两个abc的子序列满足,取下标较大的,故返回3。
备注:
若在source中找不到target,则输出-1。
解题思路:从右边往左边找(起点应该为len2 - len1),如果找到则是最大下标。
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
-
- int main()
- {
- char str1[101] = {0};
- char str2[500001] = {0};
-
- gets(str1);
- gets(str2);
-
- int len1 = strlen(str1);
- int len2 = strlen(str2);
- if (len2 < len1) {
- printf("len err\n");
- return -1;
- }
-
- int idx_1;
- for (int i = len2-len1; i >= 0; i--) {
- idx_1 = 0;
- if (str2[i] != str1[idx_1]) {
- continue;
- }
- idx_1++;
- if (idx_1 > len1) {
- continue;
- }
- int idx_2 = i + 1;
- while (idx_2 < len2 && idx_1 < len1) {
- if (str1[idx_1] == str2[idx_2]) {
- idx_1++;
- }
- idx_2++;
- if (idx_1 == len1) {
- printf("%d\n", i);
- return 0;
- }
- }
-
- }
-
- printf("-1\n");
- return 0;
- }