leetcode -- Minimum Window Substring

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.

[解题思路]

双指针问题,维护两个指针:start, end; 当start 和 end所围的字符串包含T时,此时将start尽可能往后移以寻找下一个window

本题一开始做不出来的问题在于如何移动start,即start移动的终止条件是什么?

line 27-28 是while循环的终止条件

 1 public String minWindow(String S, String T) {
 2         // Start typing your Java solution below
 3         // DO NOT write main() function
 4         if (S == null || T == null || S.length() == 0 || T.length() == 0) {
 5             return "";
 6         }
 7         int[] needToFind = new int[256];
 8         int[] hasFound = new int[256];
 9 
10         for (int i = 0; i < T.length(); i++) {
11             needToFind[T.charAt(i)]++;
12         }
13 
14         int minWinLen = Integer.MAX_VALUE;
15         int count = 0, tLen = T.length();
16         int winBeg = 0, winEnd = 0;
17         for (int begin = 0, end = 0; end < S.length(); end++) {
18             if (needToFind[S.charAt(end)] == 0) {
19                 continue;
20             }
21             hasFound[S.charAt(end)]++;
22             if(hasFound[S.charAt(end)] <= needToFind[S.charAt(end)]){
23                 count ++;
24             }
25             
26             if(count == tLen){
27                 while(needToFind[S.charAt(begin)] == 0 ||
28                         hasFound[S.charAt(begin)] > needToFind[S.charAt(begin)]){
29                     if(hasFound[S.charAt(begin)] > needToFind[S.charAt(begin)]){
30                         hasFound[S.charAt(begin)]--;
31                     }
32                     begin ++;
33                 }
34                 
35                 int winLen = end - begin + 1;
36                 if(winLen < minWinLen){
37                     winBeg = begin;
38                     winEnd = end;
39                     minWinLen = winLen;
40                 }
41             }
42         }
43 
44         if (count == T.length()) {
45             return S.substring(winBeg, winEnd + 1);
46         }
47 
48         return "";
49     }

 

ref

http://leetcode.com/2010/11/finding-minimum-window-in-s-which.html

转载于:https://www.cnblogs.com/feiling/p/3301385.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值