Monday, August 24, 2015

Leetcode: Minimum Window Substring (hash table)(two pointers)

PROBLEM:
https://leetcode.com/problems/minimum-window-substring/



----------------------------------
The general idea is to use map and two pointers. Use two pointer to form a sliding window while the value between is processed through a map, or hash table.

1. we build a map, tMap, for t;
2. using two pointers: left and right to form a windon:
3.  when moving right we do
       tMap[s[r]]--; 
    for each step, until all value in tMap is <=0;

4.  then moving left until any value in tMap reaches 1, which means the current minimal window is found.

5. repeat until the end.


  ////////////////////////////////////////////////////////////////////
// codes
class Solution {
public:
       string minWindow(string s, string t) {

              unordered_map<char, int> tMap;
              int ss = s.size(), st = t.size();
              //check input
              if (ss<st)return "";

              for (int i = 0; i<st; i++){
                     tMap[t[i]]++;
              }
              //search
              int l = 0, r = 0, lflag = 0, rflag = 1, count = 0, sm = tMap.size();
              int a[3] = { ss + 1, 0, ss + 1 };
              while (r<ss + 1 && count <= st){
                     //move right
                     if (rflag == 1){
                           tMap[s[r]]--;
                          
                           if (tMap[s[r]] == 0)count++;//counted when an item is removed
                           if (count == sm){//check whether all items in t have been found
                                  lflag = 1;
                                  rflag = 0;
                           }
            r++;
                     }
                     //move left
                     if (lflag == 1){
                           tMap[s[l]]++;
                     //when any value reaches 1, that means current minimal window is reached
                           if (tMap[s[l]] == 1){
                                  if (r - 1 - l + 1<a[2]){
                                         a[0] = l; a[1] = r - 1; a[2] = r - 1 - l + 1;
                                  }
                                  lflag = 0;
                                  rflag = 1;
                                  count--;
                           }
                           l++;
                     }
                     //when to jump out
                     if (r == ss && count<sm)break;
              }

              if (a[0] == ss + 1)return "";
              else{
                     string res(s, a[0], a[2]);
                     return res;
              }

       }

};

No comments:

Post a Comment