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

076 Minimum Window Substring 最小窗口子字符串

时间:2018-04-03 23:54:55      阅读:285      评论:0      收藏:0      [点我收藏+]

标签:and   problem   com   str   order   size   esc   http   一个   

给定一个字符串 S 和一个字符串 T,找到 S 中的最小窗口,它将包含复杂度为 O(n) 的 T 中的所有字符。
示例:
S = "ADOBECODEBANC"
T = "ABC"
最小窗口是 "BANC".
注意事项:
如果 S 中没有覆盖 T 中所有字符的窗口,则返回空字符串 ""。
如果有多个这样的窗口,你将会被保证在 S 中总是只有一个唯一的最小窗口。
详见:https://leetcode.com/problems/minimum-window-substring/description/

class Solution {
public:
    string minWindow(string s, string t) {
        if (t.size() > s.size())
        {
            return "";
        }
		string res = "";
		int left = 0;
		int count = 0;
		int minLen = s.size() + 1;
		unordered_map<char, int> m;
		for (int i = 0; i < t.size(); i++)
        {
            if (m.find(t[i]) != m.end())
            {
				++m[t[i]];
            }
			else
            {
                m[t[i]] = 1;
            }
        }
		for (int right = 0; right < s.size(); right++)
        {
            if (m.find(s[right]) != m.end())
            {
				--m[s[right]];
				if (m[s[right]] >= 0)
                {
                    ++count;
                }
				while (count == t.size())
				{
					if (right - left + 1 < minLen)
					{
						minLen = right - left + 1;
						res = s.substr(left, minLen);
					}
					if (m.find(s[left]) != m.end())
					{
						++m[s[left]];
						if (m[s[left]] > 0)
                        {
                            --count;
                        }
					}
					++left;
				}
			}
        }
		return res;
    }
};

 详见:https://www.cnblogs.com/grandyang/p/4340948.html

076 Minimum Window Substring 最小窗口子字符串

标签:and   problem   com   str   order   size   esc   http   一个   

原文地址:https://www.cnblogs.com/xidian2014/p/8711232.html

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