leetcode - Minimum Window Substring
2013-12-14 21:45 张汉生 阅读(187) 评论(0) 编辑 收藏 举报
1 class Solution { 2 public: 3 //reference: http://www.cnblogs.com/remlostime/archive/2012/11/16/2774077.html 4 string minWindow(string S, string T) { 5 int flag[128]; 6 memset(flag, 0, sizeof(flag)); 7 int lenT = T.length(); 8 if (lenT <= 0) 9 return ""; 10 int n=0; 11 for (int i = 0; i < lenT; i++){ 12 int index = (int)(T.at(i)); 13 if (flag[index] == 0) 14 n++; 15 flag[index]++; 16 } 17 int alFlag[128]; 18 memset(alFlag, 0, sizeof(alFlag)); 19 int numAl = 0; 20 const char * start = S.c_str(); 21 const int maxNum = 1000000000; 22 int rltSize = maxNum; 23 const char* startPos = NULL; 24 const char * end = start; 25 while (*end != '\0'){ 26 int index = (int)(*end); 27 alFlag[index]++; 28 if (alFlag[index] == flag[index]) 29 numAl++; 30 if (numAl == n){ 31 while (start <= end){ 32 if (rltSize > end - start + 1){ 33 rltSize = end - start + 1; 34 startPos = start; 35 } 36 int ind = (int)(*start); 37 alFlag[ind]--; 38 if (flag[ind] !=0 && alFlag[ind] == flag[ind]-1) 39 numAl--; 40 if (numAl < n){ 41 start++; 42 break; 43 } 44 start++; 45 } 46 } 47 end++; 48 } 49 if (startPos == NULL) 50 return ""; 51 string rlt=""; 52 while (rltSize-- > 0) 53 rlt += *(startPos++); 54 return rlt; 55 } 56 };