Notes:

1. When check left shifting, do not use continue, but break it!!! Otherwise, you wil fall into infinite loop

2. Initialize the map with T, not S!!!!

 1 class Solution {
 2 public:
 3     string minWindow(string S, string T) {
 4         int len = S.size(), count = 0, length = INT_MAX;
 5         string result;
 6         if (len == 0 || len < T.size()) return "";
 7         unordered_map<char, int> dict;
 8         for (char c : T) {
 9             if (dict[c]) dict[c]++;
10             else dict[c] = 1;
11         }
12         for (int left = 0, right = 0; right < len; right++) {
13             if (dict.find(S[right]) != dict.end()) {
14                 dict[S[right]]--;
15                 if (dict[S[right]] == 0) {
16                     count++;
17                 }
18             }
19             
20             while (left < len) {
21                 if (dict.find(S[left]) != dict.end() && dict[S[left]] >= 0) break;
22                 if (dict.find(S[left]) != dict.end()) {
23                     dict[S[left]]++;
24                 }
25                 left++;
26             }
27             
28             if (count == dict.size() && length > (right - left + 1)) {
29                 result = S.substr(left, right-left+1);
30                 length = right - left + 1;
31             }
32         }
33         return result;
34     }
35 };

 

posted on 2015-03-21 08:03  keepshuatishuati  阅读(149)  评论(0编辑  收藏  举报