2015年4月13日 星期一

TIOJ 1489 E.核心字串

#include <cstdio>
#include <cstdlib>
#include <string.h>
using namespace std;

char a[1000005], ans[1000005];
int cnt[26];
int ans_st;
int ans_l;

bool check(){
    for (int i = 0; i < 26; ++i)
        if(cnt[i] == 0)
            return false;
    return true;
}

void update(int st, int len){
    if(len < ans_l){
        ans_st = st;
        ans_l = len;
    }
}

int main(){
    int n;
    scanf("%d", &n);
    while(n > 0){
        scanf("%s", a);
        
        memset(cnt, 0, sizeof(cnt));

        ans_l = 1e9;
        int l = 0, r = 0;
        for (int i = 0; i < n; ++i)
        {
            r = i;
            cnt[a[i] - 'a']++;

            if(!check())
                continue;

            while(1){
                update(l, r - l + 1);
                l++;
                if(--cnt[a[l - 1] - 'a'] == 0)
                    break;
            }
        }

        if(ans_l != 1e9){
            ans[ans_l] = '\0';
            strncpy(ans, a + ans_st, ans_l);
        }

        printf("%s\n", ans_l != 1e9 ? ans:"not found");

        scanf("%d", &n);
    }  
} 

沒有留言:

張貼留言