PAT 2020年冬季 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 <iostream>
#include <cstring>
using namespace std;

int main() {
	string s,p,ans;
	cin>>s>>p;
	int minLen=0x7fffffff;
	for(int i=0; i<s.length(); i++) {
		if(s[i]!=p[0]) continue;
		string temp;
		int cnt=0;
		for(int j=i; j<s.length(); j++) {
			if(cnt==p.length()) break;
			if(s[j]==p[cnt]) cnt++;
			temp+=s[j];
		}
		if(cnt==p.length()&&temp.length()<minLen) {
			minLen=temp.length();
			ans=temp;
		}
	}
	cout<<ans;
	return 0;
}
posted @ 2021-03-11 18:21  coderJ_ONE  阅读(137)  评论(0编辑  收藏  举报