Minimum Window Substring
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.
题目的意思是说,要在S中找一个最短的子串,该子串包含了T中的所有字符,如上面所示<span style="font-size:18px;">class Solution { public: string minWindow(string S, string T) { int totalnumber[256]={0}; int aredyfind[256]={0}; int count=0;//用来表示当前已经找到的总字符,如果都找到,count为T.length() int i,start; int winstart=-1; int winend=S.length(); for(i=0;i<T.size();i++) { totalnumber[T[i]]++; } for(i=0,start=0;i<S.size();i++) { if(totalnumber[S[i]]!=0) //这里表示字符S[i]属不属于T,如果不属于T那么直接跳过 { aredyfind[S[i]]++; if(aredyfind[S[i]]<=totalnumber[S[i]]) count++; if(count==T.length()) //表示已经找到了一个合法的窗口 { while(totalnumber[S[start]]==0||aredyfind[S[start]]>totalnumber[S[start]]) //这里判断start处的字符属不属于T或者属于T但是重复出现了,两种情况都是要缩小窗口的 { if(aredyfind[S[start]]!=0) aredyfind[S[start]]--; start++; } if(winend-winstart>i-start) { winend=i; winstart=start; } aredyfind[S[start]]--; //上面表示已经找到了一个start开始 i结束的当前最优,然后start++,此时必然有字母被删除了,所以回到开始i出循环,i往后遍历来寻找哪个被删除的字母 start++; count--; } } } return winstart==-1?"":S.substr(winstart,winend-winstart+1); } };</span>
Minimum Window Substring leetcode
原文:http://blog.csdn.net/yujin753/article/details/41809705