题目描述:
Given strings S and T, find the minimum (contiguous) substring W of S, so that T is a subsequence of W.
If there is no such window in S that covers all characters in T, return the empty string "". If there are multiple such minimum-length windows, return the one with the left-most starting index.
Example 1:
Input: S = "abcdebdde", T = "bde" Output: "bcde" Explanation: "bcde" is the answer because it occurs before "bdde" which has the same length. "deb" is not a smaller window because the elements of T in the window must occur in order.
Note:
- All the strings in the input will only contain lowercase letters.
- The length of
Swill be in the range[1, 20000]. - The length of
Twill be in the range[1, 100].
class Solution {
public:
string minWindow(string S, string T) {
int m=S.size();
// next[i][t]表示在S[i:m]的范围内,t第一次出现的下标,t是T中字符
vector<vector<int>> next(m,vector<int>(26,-1));
vector<int> index(26,-1); // 记录遍历过程中t上一次出现的下标
for(int i=m-1;i>=0;i--) // 必须倒着遍历S
{
index[S[i]-'a']=i;
for(int j=0;j<26;j++)
{
next[i][j]=index[j];
}
}
int min_length=INT_MAX;
string result;
for(int i=0;i<m;i++)
{
int j=0;
int begin=next[i][T[j]-'a'];
int end=begin;
j++;
while(j<T.size())
{ // 当迭代还没有完成,而已经找不到对应字母的下标时,可以直接返回结果
// 因为i和j是递增的,之后的迭代也不可能得到合法的结果
if(end>=m-1||end==-1) return result;
end=next[end+1][T[j]-'a']; // 利用end搜索下一个end,注意起点要改为end+1
j++;
}
if(end>=m||end==-1) return result; // 最后一个end也需要检查
if(end-begin+1<min_length)
{
min_length=end-begin+1;
result=S.substr(begin,min_length);
}
}
return result;
}
};
本文介绍了一种算法,用于在字符串S中找到包含字符串T所有字符的最短子串W。通过构建next矩阵来预处理S,算法能有效地解决此问题。示例中,输入S=abcdebdde,T=bde,输出为bcde。

被折叠的 条评论
为什么被折叠?



