Minimum Window Substring
来源:互联网 发布:淘宝锋利小刀 编辑:程序博客网 时间:2024/05/01 22:00
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.
基本解题思路:
sliding window: start from a window that is tight.
Try moving the start forward and then see if it is possible to tighten the window.
public class Solution { public String minWindow(String S, String T) { // solve this problem by sliding window int tlen = T.length(), slen = S.length(); int[] cnt = count(T); int[] covered = new int[256]; int min_len = slen+1, start = 0; String ans = ""; int cover = 0; for(int i=0; i<slen; i++){ char ch = S.charAt(i); if(cnt[ch] > 0){ if(covered[ch] < cnt[ch]) cover++; covered[ch] ++; } if(cover == tlen){ // can be the end of the minimum substring while(start < i){ char chs = S.charAt(start); if(cnt[chs] > 0 && cnt[chs] == covered[chs]) break; else if(cnt[chs] > 0){ covered[chs]--; } start++; } int len = i-start+1; if(len < min_len){ min_len = len; ans = S.substring(start, i+1); } } } return ans; } private int[] count(String str){ int[] cnt = new int[256]; int len = str.length(); for(int i=0; i<len; i++){ char ch = str.charAt(i); cnt[ch] ++; } return cnt; }}
Space Complexity: O(1) though the count array/hashmap could take 256, but it is still constant
Time complexity: O(max(S.len, T.len)), need to scan T once and scan S twice.
- 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
- Java获取本机IP列表的几种方法
- 常用的Javascript设计模式
- 老杜(杜昶旭)GRE填空笔记部分整理-by“ 1哥”+ TTC相关资料
- Find Minimum in Rotated Sorted Array II
- 【Leetcode】Pow(x,n)
- Minimum Window Substring
- 【水打表】#69 A. Panoramix's Prediction
- POJ 3715:计算工作天数
- 深度优先搜索算法(DFS,Depth First Search)的PHP实现
- 微软宣布它爱 Linux
- Robot 第五周(机体局部动作测试和研究动力学建模)
- 在android中使用achartengine来绘制各种图表
- android输入法中的imeoption
- Ubuntu12.04系统编译Android4.4源码