leetcode 76 Minimum Window Substring
2015-09-14 19:38
531 查看
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
For example,
S = “ADOBECODEBANC”
T = “ABC”
Minimum window is “BANC”.
Note:
If there is no such window in S that covers all characters in T, return the emtpy string “”.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
Hide Tags Hash Table Two Pointers String
Hide Similar Problems (H) Substring with Concatenation of All Words (M) Minimum Size Subarray Sum (H) Sliding Window Maximum
For example,
S = “ADOBECODEBANC”
T = “ABC”
Minimum window is “BANC”.
Note:
If there is no such window in S that covers all characters in T, return the emtpy string “”.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
Hide Tags Hash Table Two Pointers String
Hide Similar Problems (H) Substring with Concatenation of All Words (M) Minimum Size Subarray Sum (H) Sliding Window Maximum
代码
class Solution { public: string minWindow(string s, string t) { if(s.length()<t.length()){ return ""; } //t中可能存在重复字符串,要统计每个字符的数目 map<char,int> needToFind; map<char,int> hasFound; for(int i=0;i<t.length();i++){ if(needToFind.find(t[i])!=needToFind.end()){ needToFind[t[i]]+=1; }else{ needToFind[t[i]]=1; hasFound[t[i]]=0; } } char c; string ret=""; bool retValid=false; for(int count=0,begin=0,end=0;end<s.size();end++){ c=s[end]; //对s,只处理t中存在的字符,其他的字符直接忽略 if(needToFind.find(c)!=needToFind.end()){ //处理当前字符,更新count和hasFound if(hasFound[c]<needToFind[c]){ count++; } hasFound[c]++; //begin-end包含全部t的字符 if(count==t.length()){ //先扔掉begin-end中:begin处,不是t中的和hasFound》needTofind while(needToFind.find(s[begin])==needToFind.end() || hasFound[s[begin]]>needToFind[s[begin]]){ if(needToFind.find(s[begin])!=needToFind.end() && hasFound[s[begin]]>needToFind[s[begin]]){ hasFound[s[begin]]--; } begin++; } //检查这个子串是否是最短的 if(retValid==false){ retValid=true; ret=s.substr(begin,end-begin+1); }else if(end-begin+1 < ret.length()){ ret=s.substr(begin,end-begin+1); } } } } return ret; } };
相关文章推荐
- ubuntu linux14.04添加系统调用
- UNICODE与ASCII
- C++,C程序设计入门——《高质量程序设计第4章》
- 第三周项目三求合集并集
- springmvc整合mybatis框架源码 bootstrap html5 mysql oracle
- 如何成为一名优秀的软件测试工程师
- C++Primer第五版 5.4.1节练习
- C++开发中指针易错点
- POJ 1577 Falling Leaves 二叉树
- 后缀数组模板
- 将输入字符串中每个单词的首字母变成大写
- UNICODE,GBK,UTF-8
- 导致页面顶部空白一行解决方法
- java动态规划最大子段和
- Maven的HTTP代理设置
- volley的正确使用方式
- Android之单线程下载与多线程下载
- C++Primer第五版 5.3.2节练习
- Redrain duilib中的名字空间问题
- HDU--1213并查集