LeetCode #727. Minimum Window Subsequence

本文介绍了一种算法,用于在字符串S中找到包含字符串T所有字符的最短子串W。通过构建next矩阵来预处理S,算法能有效地解决此问题。示例中,输入S=abcdebdde,T=bde,输出为bcde。

题目描述:

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 S will be in the range [1, 20000].
  • The length of T will 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;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值