最短子串

来源:互联网 发布:开淘宝店的具体步骤 编辑:程序博客网 时间:2024/05/17 04:57


问题描述:

输入两个字符串S,T(均由大写英文字母组成,且length(S)>=length(T)),要求在S中找出包含T中所有字符的最短子串,假设最短子串唯一。(有兴趣的同学可以尝试用O(n)的时间复杂度解决该问题,注:本题无该要求)

输入描述:

输入为两行。第一行为字符串S;第二行为字符串T

输出描述:

输出S的一个子串,该子串为包含T中所有字符的最短子串,如果不存在这样的子串,则输出"No"

输入样例1:

ADOBECODEBANCABC

输出样例1:

BANC

输入样例2:

ABCDEFACDABGH

输出样例2:

No


#include <iostream>#include <cstring>#include <algorithm>using namespace std;char t[1001], w[1001];int nt[1001], pos[1001];int d[1001];int main(){    int tn, wn;    memset(nt, -1, sizeof(nt));    memset(pos, -1, sizeof(pos));    memset(d, 0, sizeof(d));    cin >> t >> w;    tn = strlen(t);    wn = strlen(w);    for(int i = tn-1; i >= 0; i--)    for(int j = 0; j <= wn; j++) if(t[i] == w[j]){nt[i] = pos[j]; pos[j] = i;}    for(int i = 0; i < wn; i++) {        while(pos[i]!= -1 && d[pos[i]]) pos[i] = nt[pos[i]];        if(pos[i] == -1) {cout << "No"; return 0;}        d[pos[i]] = 1;        //cout << pos[i] << " ";    }    sort(pos, pos + wn);    int fir = pos[0], las = pos[wn-1];    int dist = las - fir;    while(pos[0] != -1){        while(pos[0]!= -1 && d[pos[0]]) pos[0] = nt[pos[0]];        if(pos[0] == -1) break;        d[pos[0]] = 1;        sort(pos, pos + wn);        if(dist > pos[wn-1] - pos[0]) {            fir = pos[0]; las = pos[wn-1];            dist = las - fir;        }    }    for(int i = fir; i <= las; i++) cout << t[i];}




阅读全文
0 0