Minimum Window Substring
来源:互联网 发布:nginx tcp代理 编辑:程序博客网 时间:2024/04/29 14:58
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 empty string ""
.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
分析:
同样是滑动窗口问题;
这里需要借助map,初始map中存放T中的字符以及字符个数,然后right指针开始向后遍历,直到窗口中含有了T中的所有字符,这里以一个变量count进行计数;当然只有在right指针指向的字符在T中而且该字符在map中对应的数量大于0时才能count+1,因为如果其对应的数量已经等于0了,说明窗口中已经包含了T中该字符的数量,当前这个是多余的;
当count等于T的长度时,计算窗口大小,并且与当前的最小窗口大小进行比价,同时记录窗口起始位置;left指针开始起作用,逐渐往前遍历直到含有T中字符,对map进行补全;直到不再含有T中的某一个字符为止;
发现map的使用真心巧妙!!!
参考代码:
http://blog.csdn.net/linhuanmars/article/details/20343903
public class Solution { public String minWindow(String S, String T) { if(S==null || S.length()==0) return ""; HashMap<Character, Integer> map = new HashMap<Character, Integer>(); for(int i=0; i<T.length();i++) { if(map.containsKey(T.charAt(i))) { map.put(T.charAt(i),map.get(T.charAt(i))+1); } else { map.put(T.charAt(i),1); } } int left = 0; int count = 0; int minLen = S.length()+1; int minStart = 0; for(int right=0; right<S.length();right++) { 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(right-left+1<minLen) { minLen = right-left+1; minStart = left; } if(map.containsKey(S.charAt(left))) { map.put(S.charAt(left), map.get(S.charAt(left))+1); if(map.get(S.charAt(left))>0) { count--; } } left++; } } } if(minLen>S.length()) { return ""; } return S.substring(minStart,minStart+minLen);}}
- 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
- 九月英语总结——不同凡响
- 基于注解的 Spring MVC 简单入门
- CF 581F 树形dp
- activity生命周期
- Java串口通信(代码+测试工具)
- Minimum Window Substring
- iOS8中使用CoreLocation定位
- 序言
- 关于CSpreadSheet的若干问题
- Hadoop Hive sql语法详解
- JCreator工具三种方法(1.实现Servlet接口2.继承GenericServlet3.继承HttpServlet)开发Servlet
- 小马哥---山寨小米平板电脑刷机拆机主板图与开机识别图 界面图 多图展示 精仿版本 购买警惕
- Open MPI的目标、概念及实现
- Coco2d-js/Cocos2d-html5中Android返回键实现