码迷,mamicode.com
首页 > Windows程序 > 详细

LeetCode Minimum Window Substring

时间:2014-09-16 21:46:51      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   div   art   sp   

class Solution {
private:
    int shd_cnt[256];
    int cur_cnt[256];
public:
    string minWindow(string S, string T) {
        int slen = S.length();
        int tlen = T.length();
        
        // array to store char stat info of string T
        for (int i=0; i<256; i++) shd_cnt[i] = cur_cnt[i] = 0;
        // collect char stat info of string T
        for (int i=0; i<tlen; i++) shd_cnt[T[i]]++;
        
        int shd_match_cnt = 0, cur_match_cnt = 0;
        for (int i=0; i<256; i++) shd_match_cnt += shd_cnt[i] != 0;
        
        int start = 0, end = 0;
        
        int mlen = INT_MAX, ps = 0, pe = 0;
        
        bool updated = true;
        
        while (updated) {
            updated = false;
            while (cur_match_cnt == shd_match_cnt && start < slen) {
                if (end - start < mlen) {
                    mlen = end - start;
                    ps = start, pe = end;
                }
                
                char ch = S[start];
                // whether current char is critical for matching
                // if so it could not be omitted
                if (cur_cnt[ch] - 1 < shd_cnt[ch]) break;

                updated = true;
                cur_cnt[ch]--;
                start++;
            }
            
            if (end < slen) {
                updated = true;
                char ch = S[end++];
                
                if (++cur_cnt[ch] == shd_cnt[ch]) { // using strict equal
                    cur_match_cnt++;
                }
            }
        }
        return S.substr(ps, pe - ps);
    }
};

"滑动窗口"...

LeetCode Minimum Window Substring

标签:style   blog   color   io   ar   for   div   art   sp   

原文地址:http://www.cnblogs.com/lailailai/p/3975780.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!