Minimum Window Substring Java

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.


 Key to Solve: Two pointer Window's range method + HashMap,
    Similar idea with Substring with Concatenation of All Words & Longest Substring Without Repeating Characters
    1. Create a Map(key: Character, Value: Frequency) of T
    2. move right window's point while < S.length
    2. move left window's point under condition of full match were found
    3. optimize the min window string
    Time: O(2*N)=O(N)
    Space: O(L) L is size of T


public class Solution {
    public String minWindow(String S, String T) {
      String output="";
    if(S.length()==0 || T.length()==0) return "";
    HashMap<Character,Integer> map=new HashMap<Character, Integer>();
    int matchCount=0;
    int minLen=S.length()+1;
    int left=0,right=0;

    //create a Map
    for(int i=0;i<T.length();i++){
        char c=T.charAt(i);
        if(map.containsKey(c)){
            map.put(c,map.get(c)+1);
        }else {
            map.put(c,1);
        }
    }
    while(right<S.length()) {
        char c = S.charAt(right);
        if (map.containsKey(c)) {
            //System.out.println("c: "+c);
            map.put(c, map.get(c)-1);
            if (map.get(c) >= 0) {
                matchCount++;
            }
            //Full Match were found
            while (matchCount == T.length()) {
                char cl=S.charAt(left);
                if (map.containsKey(cl)) {
                    //record the character frequency
                    map.put(S.charAt(left), map.get(cl) + 1);
                    //optimize the min window String
                    if (map.get(cl)>0) {
                        if (minLen > right - left + 1) {
                            output = S.substring(left, right + 1);
                            minLen = right - left + 1;
                        }
                        matchCount--;
                    }
                }
                left++;
            }
        }
        right++;    //skip un-relevant character
    }
    return output;
    }
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值