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 @   coderJ_ONE  阅读(147)  评论(0)    收藏  举报
编辑推荐:
· 微服务架构学习与思考:微服务拆分的原则
· 记一次 .NET某云HIS系统 CPU爆高分析
· 如果单表数据量大,只能考虑分库分表吗?
· 一文彻底搞懂 MCP:AI 大模型的标准化工具箱
· 电商平台中订单未支付过期如何实现自动关单?
阅读排行:
· .NET 阻止Windows关机以及阻止失败的一些原因
· 博客园2025新款「AI繁忙」系列T恤上架
· Avalonia跨平台实战(二),Avalonia相比WPF的便利合集(一)
· C# LINQ 快速入门实战指南,建议收藏学习!
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(6)
点击右上角即可分享
微信分享提示