[Leetcode] Minimum Window Substring
2014-04-03 15:30
567 查看
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 =
T =
Minimum window is
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.
要求复杂度为O(n),只要扫描一遍数组即可,大致做法是设一个start和一个end表示窗口的起始与结束位置,先从先向后匹配end,当找到可容纳T的窗口后再从前而匹配start,去掉无用的元素。具体做法为使用两个哈希表hasCvd与need2Cv,分别表示已经找到的某个字母的匹配与需要找到的匹配。
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.
要求复杂度为O(n),只要扫描一遍数组即可,大致做法是设一个start和一个end表示窗口的起始与结束位置,先从先向后匹配end,当找到可容纳T的窗口后再从前而匹配start,去掉无用的元素。具体做法为使用两个哈希表hasCvd与need2Cv,分别表示已经找到的某个字母的匹配与需要找到的匹配。
class Solution { public: string minWindow(string S, string T) { int start = 0, end = 0; int min_start = 0, min_end = 0; int min_len = INT_MAX; vector<int> hasCvd(256 ,0); vector<int> need2Cv(256, 0); for (int i = 0; i < T.length(); ++i) { ++need2Cv[T[i]]; } int validCnt = 0; for (end = 0; end < S.length(); ++end) { ++hasCvd[S[end]]; if (need2Cv[S[end]] == 0) continue; if (hasCvd[S[end]] <= need2Cv[S[end]]) ++validCnt; if (validCnt == T.length()) { while(hasCvd[S[start]] > need2Cv[S[start]]) { --hasCvd[S[start]]; ++start; } if(min_len > (end - start)) { min_len = end - start + 1; min_start = start; min_end = end; } } } return (min_len == INT_MAX) ? "" : S.substr(min_start, min_len); } };
相关文章推荐
- 当我处于这样的情况庆幸有你的一直陪伴
- mysql的left join和right join和inner join等表联接详解
- 解析垃圾渗滤液成分以及处理方案
- 开场白
- 进程间的通信(互斥锁、条件变量、读写锁、文件锁、信号灯)
- 简短的js判断手机横竖屏
- Linux设备驱动程序学习(3-补)-Linux中的循环缓冲区
- Android下常见的内存泄漏
- STM32之CAN--CAN ID过滤器分析
- java中的MessageDigest类
- ctags 使用细节
- Spring 的Hibernate事务管理机制 .
- 面试题收集——Java基础部分(一)
- attributes
- IOS applicationWillResignActive
- 总结造纸业中水回用方案及处理工艺
- 论坛源码推荐(4月3日): CoreData 快速集成 神奇输入法FleksySDK
- linux 安装Nginx-0.8.54
- mini_magick+jquery.Jcrop+jquery.form.min
- Linux设备驱动程序学习(11)-中断处理