题解 | #寻找完成任务所需最短时间#

寻找完成任务所需最短时间

https://www.nowcoder.com/practice/107342346ad44329a35c7e5b890e7d40

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @param t string字符串 
     * @return string字符串
     */
    string minWindow(string s, string t) {
        // write code here
        map<char, int> mp;
        int min_len = 1e8;
        if (t.size() > s.size()) return "";
        int left = 0, right = 0;
        int start = 0, end = 0;
        for (int i = 0; i < t.size(); i++) {
            mp[t[i]]++;
        }
        int need = t.size();
        for (; right < s.size(); right++) {
            char c = s[right];
            if (t.find_first_of(c) != string::npos) {
                if (mp[c] > 0) {
                    need--;
                }
                mp[c]--;
            }
            while (need == 0) {
                if (right-left+1 < min_len) {
                    min_len = right-left+1;
                    start = left, end = right;
                }
                char c = s[left];
                if (t.find_first_of(c) != string::npos) {
                    if (mp[c] >= 0) {
                        need++;
                    }
                    mp[c]++;
                }
                left++;
            }
        }
        if (min_len == 1e8) return ""; 
        return s.substr(start, end-start+1);
    }
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务