【PAT甲级、乙级2020冬季】7-5 子串与子列 Subsequence in Substring (25 分)

全网都没有一道题是找最短子串的 < @ _ @ >

一开始只有18分。我靠,做甲级的时候优化了一下,居然AC了【喜从中来~】

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 atpaaabpabttpabt 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.

子串是一个字符串中连续的一部分,而子列是字符串中保持字符顺序的一个子集,可以连续也可以不连续。例如给定字符串 atpaaabpabttpabt是一个子串,而 pat 就是一个子列。

现给定一个字符串 S 和一个子列 P,本题就请你找到 S 中包含 P 的最短子串。若解不唯一,则输出起点最靠左边的解。

输入格式:

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.

输入在第一行中给出字符串 S,第二行给出 P。S 非空,由不超过 10​4​​ 个小写英文字母组成;P 保证是 S 的一个非空子列。

输出格式:

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

在一行中输出 S 中包含 P 的最短子串。若解不唯一,则输出起点最靠左边的解。

输入样例:

atpaaabpabttpcat
pat

输出样例:

pabt

分析:

很直接,暴力法破题。先把字符串中所有的子串中的第一个字符都找到,并用数组记录下来,该数组长度即字符串中子列可能的个数。然后在字符串中依次查找,取长度最小值的子列输出即可。

代码:

#include<bits/stdc++.h>   //好东西,实在是令人省心
using namespace std;
int main(){
    string s,p;
    cin>>s>>p;
    vector<int> v;
    for(int i=0;i<s.size();i++)
        if(s[i]==p[0]) v.push_back(i);//找出整个字符串和子串第一个字符相同的所有元素的下标
    int minlen=s.size()+1,mini=0; 
    for(int i=0;i<v.size();i++){//s中可能的子串数
        int cnt=1;//已经找完第一个了 
        for(int j=v[i]+1;j<s.size();j++){
            if(s[j]==p[cnt]) cnt++; //找子串的第1~p.size()-1个字符
            if(cnt==p.size()){//找完了 
            	if(j-v[i]<minlen){
            		minlen=j-v[i];
            		mini=v[i];
				}	
				break;
			}
        } 
    }
    for(int i=mini;i<=mini+minlen;i++)
		cout<<s[i];
    return 0;
}

其实我想说的是,细节才是最重要的!!!做的时候眼花缭乱的,总是把i当成j,把j当成i,我都无语了。。。

扫描二维码关注公众号,回复: 12747087 查看本文章

说白了就是道逻辑题。。。

但果然我不擅长的就是复杂的逻辑题~

猜你喜欢

转载自blog.csdn.net/WKX_5/article/details/114480779