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

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

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

#include <unordered_map>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @param t string字符串 
     * @return string字符串
     */
    string minWindow(string s, string t) {
        // write code here
        // 哈希表+遍历
        unordered_map<char,int> um;
        for(auto ch:t)
            ++um[ch];

        int len_s = s.size();
        int len_t = t.size();
        string str = "";
        for(int i=0; i<len_s-len_t+1; ++i)
        {
            // 剪枝,不用每个字符都作为起点遍历
            if(um.count(s[i]))
            {
                unordered_map<char, int> temp = um;
                for(int j=i; j<len_s; ++j)
                {
                    if(temp.count(s[j]))
                    {
                        --temp[s[j]];
                        if(temp[s[j]]==0)
                            temp.erase(s[j]);
                    }
                    // if(temp.empty())
                    //     cout << s.substr(i,j-i+1) << endl;
                    // 全部找到了
                    if(temp.empty() && ((int)str.size()>j-i+1 || str.empty()))
                    {
                        str = s.substr(i,j-i+1);
                        break;
                    }
                }
            }
        }

        return str;
    }
};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务