Minimum Window Substring
来源:互联网 发布:中国云计算行业分析 编辑:程序博客网 时间:2024/06/15 07:51
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.
思路:
1. 维护一个map<Character, Integer>来表示每个字母还可以出现的次数。开始的时候建立map,字母对应在target string里出现的次数。另外一个count
2. 对长sring扫描,如果遇到map里存在的字母,就对对应的值-1 (注意这里可以是负数,表示该位字母出现多次,但是我们不计算在总count里).如果该值>=0则总count++,表示总共找到的字母增加一位。
3. 如果count = target.length()说明已经全部找到,这时窗口左边向右移动,如果对应的值在map里,那就把map里的value+1,因为我们需要寻找的字母又少了一个。在value+1后,如果count<target.length(),说明我们又可以开始寻找下一个了,就先计算一下当前match的长度:right-left+1
public String minWindow(String S, String T) { if (T.length() == 0) { return ""; } int count = 0; Map<Character, Integer> map = new HashMap<Character, Integer>(); for (int i = 0; i < T.length(); i++) { char c = T.charAt(i); if (map.get(c) == null) { map.put(c, 1); } else { map.put(c, map.get(c)+1); } } int minLen = Integer.MAX_VALUE; String result = ""; int left = 0, right = 0; while (left <= S.length() - T.length() && right < S.length()) { if (map.containsKey(S.charAt(right))) { map.put(S.charAt(right), map.get(S.charAt(right))-1); if (map.get(S.charAt(right)) >= 0) { count++; } while (count == T.length()) { if (map.get(S.charAt(left)) != null) { map.put(S.charAt(left), map.get(S.charAt(left))+1); if (map.get(S.charAt(left)) > 0) { int curLen = right-left+1; if (curLen < minLen) { minLen = Math.min(minLen, curLen); result = S.substring(left, right+1); } count--; } } left++; } } right++; } return result; }
- LeetCode: Minimum Window Substring
- LeetCode Minimum Window Substring
- LeetCode : Minimum Window Substring
- [LeetCode] Minimum Window Substring
- [Leetcode] Minimum Window Substring
- Minimum Window Substring
- LeetCode: Minimum Window Substring
- Minimum Window Substring
- [LeetCode]Minimum Window Substring
- Minimum Window Substring
- Minimum Window Substring
- [leetcode]Minimum Window Substring
- Minimum Window Substring
- Leetcode:Minimum Window Substring
- LeetCode-Minimum Window Substring
- [leetcode] Minimum Window Substring
- [leetcode] Minimum Window Substring
- leetcode Minimum Window Substring
- leetcode - Palindrome Number
- tomcat 服务器 在45秒内未启动成功
- 解决WINCE6.0新建工程编译出错的问题
- 计算机网络相关
- 模型(Model)类
- Minimum Window Substring
- 关于nova-manage service list检测服务状态原理
- Spring3.x--初始化和销毁Bean
- STL algorithm算法find(16)
- Evaluate Reverse Polish Notation
- 【刷题小记22】素数求和问题
- poj3627~贪心~排序~小水题
- Python的lambda匿名函数
- nyoj100一的个数