1

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

题目限制

image.png

题目大意

给定两个字符串S和P,输出包含P的最短S子串,如果有多个,那么就输出最左边的那个.

算法思路

使用双指针进行暴力搜索,我们使用指针i搜索字符串S不回退,指针j搜索字符串P会回退,同时使用end标记当前字符串S与P[j]待比较的位置,初始为i+1,如果s[end] == p[j],那么就++end,++j。否则就++end。如果最后j来到P的结尾位置,说明当前S的子串[i,end)包含字符串P,使用minLen记录其最短长度,同时如果在遍历的时候发现当前[i,end)的长度end-i已经大于minLen了,就说明就算后面有解也不是最优解,直接退出即可。

提交结果

image.png

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;
}

乔梓鑫
569 声望17 粉丝

主要分享个人学习经验和心得