LeetCode题解——Minimum Window Substring

本文介绍了一种在字符串S中寻找包含字符串T所有字符的最短子串的算法,复杂度为O(n)。通过使用两个映射表来跟踪目标字符和当前窗口内的字符状态,该算法能够高效地确定最小覆盖子串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

解题思路:首先找到符合条件的一个解如:ADOBEC,大小为6的window再在找到的窗口中看能否缩小范围,比如若此时找到的子窗口为AADOBEC,可缩小范围为ADOBEC,大小为6的window;然后删除第一个数,这里指A,再寻找可能组成的窗口

// Minimum Window Substring.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

class Solution {
public:
    string minWindow(string s, string t) {
        if (t.empty())
            return "";
        int t_map[256] = {0}, s_map[256] = {0};
        int t_size = 0;

        for (auto c : t)
        {
            if (t_map[c] == 0)
                t_size ++;
            t_map[c] ++;
        }
        int start = 0, end = 0, found = 0, min_start = 0, min_end = s.size() + 1;
        while (start <= end && end <= s.size())
        {
            if (found < t_size)
            {
                end ++;
                char c = s [end - 1];
                if (t_map[c] > 0 && ++s_map[c]  ==  t_map[c])
                {
                    found ++;
                }
            }else {
                start ++;
                char c = s [start - 1];
                if (t_map[c] > 0 && s_map[c]--  ==  t_map[c])
                {
                    found --;
                }
            }
            if (found == t_size && end - start < min_end - min_start)
            {
                min_start = start;
                min_end = end;
            }
        }
        if (min_end == s.size() + 1)
            return "";
        return s.substr(min_start, min_end - min_start);
    }
};


int main(int argc, char** argv)
{
	string S = "AAABCEFAABFC";
	string T = "AABC";
	Solution s;
	string ans=s.minWindow(S,T);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值