[LinkedIn] Minimum Window Substring

/*
 * Solution: 
 * 1. having left and right pointer for left end and right end of the current window
 * 2. maintain a hashmap to remember the count each char in T left to be found
 */
public String findMinWindow(String S, String T) {
 String res = "";
 if (S == null || T == null || S.length() == 0 || T.length() == 0) {
   return res;
 }
 Map<Character, Integer> hm = new HashMap<Character, Integer>();
 //initialize the hashmap
 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 count = 0;//the current total count of all chars in T
 int i = 0; // the left end of the current window
 int min = S.length() + 1;//initialize the min length to be over the length
 for (int j = 0; j < S.length(); ++j) {
   if (hm.containsKey(S.charAt(j))) {
     hm.put(S.charAt(j), hm.get(S.charAt(j)) - 1);
     if (hm.get(S.charAt(j)) >= 0) {
       count++;
     }
     while (count == T.length()) { //while we still have all the chars in the cur window
       //we only need to check when the current char exist in T
       if (hm.containsKey(S.charAt(i))) {
           //Do 2 things:
           //1. increment remaining occurrences by one
           //2. if the current char cause the occurrences to be found grow over 0
           //    a. this is potentially a min string window
           //    b. decrement the count
         hm.put(S.charAt(i), hm.get(S.charAt(i))+1);
         if (hm.get(S.charAt(i)) > 0) {
           if (min > j - i + 1) {
             res = S.substring(i, j + 1);
             min = j - i + 1;
           }
           count--;
         }
       }
       //this is in the while loop,
       // increment the left window edge when the count remains
       i++;
     }
   }
 }
 return res;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值