# PAT_甲级_2020年冬季考试 7-2 Subsequence in Substring

## 7-2 Subsequence in Substring (25 分)

A substring is a continuous part of a string. A subsequence is the part of a string that might be continuous or not but the order of the elements is maintained. For example, given the string `atpaaabpabtt`, `pabt` is a substring, while `pat` is a subsequence.

Now given a string S and a subsequence P, you are supposed to find the shortest substring of S that contains P. If such a solution is not unique, output the left most one.

### Input Specification:

Each input file contains one test case which consists of two lines. The first line contains S and the second line P. S is non-empty and consists of no more than 10^4 lower English letters. P is guaranteed to be a non-empty subsequence of S.

### Output Specification:

For each case, print the shortest substring of S that contains P. If such a solution is not unique, output the left most one.

### Sample Input:

``````atpaaabpabttpcat
pat``````

### Sample Output:

``pabt``

### AC代码

``````#include<cstdio>
#include<vector>
#include<iostream>
#include<algorithm>

using namespace std;

int main() {
string s, p;
cin >> s >> p;
int n = s.size();
int m = p.size();
int minLen = 0x3fffffff;
string ans;
for (int i = 0; i < n; ++i) {
// 起始位不同一定不行
if (s[i] != p[0]) {
continue;
}
int j = 1;
int end = i + 1;
// 判断[i,end)的子串是否有子序列b
while (j < m && end < n) {
if (s[end] == p[j]) {
++end;
++j;
} else {
++end;
}
// 当前子串的长度已经长于已保存的记录，就不需要继续判断了
if (end - i >= minLen) {
break;
}
}
// [i,end)的子串含有子序列b
if (j == m) {
int len = end - i;
if (len < minLen) {
ans = s.substr(i, len);
minLen = len;
}
}
}
cout << ans;
return 0;
}``````

566 声望
15 粉丝
0 条评论