Minimum Window Substring

本文提供了一种简洁高效的实现方式来解决最小覆盖子串问题。通过C++代码展示了如何从字符串S中找到包含字符串T所有字符的最小子串,并详细解释了算法背后的逻辑和步骤。

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

转自:

http://www.cnblogs.com/remlostime/archive/2012/11/16/2774077.html

 

这篇文章的代码是我看到写得最简洁的。

 

class Solution {
 private:
     int count1[256];
     int count2[256];
 public:
     string minWindow(string S, string T) {
         // Start typing your C/C++ solution below
         // DO NOT write int main() function
         if (T.size() == 0 || S.size() == 0)
             return "";
             
         memset(count1, 0, sizeof(count1));
         memset(count2, 0, sizeof(count2));
         
         for(int i = 0; i < T.size(); i++)
         {
             count1[T[i]]++;
             count2[T[i]]++;
         }
         
         int count = T.size();
         
         int start = 0;
         int minSize = INT_MAX;
         int minStart;
         for(int end = 0; end < S.size(); end++)
         {
             if (count2[S[end]] > 0)
             {
                 count1[S[end]]--;
                 if (count1[S[end]] >= 0)
                     count--;
             }
             
             if (count == 0)
             {
                 while(true)
                 {
                     if (count2[S[start]] > 0)
                     {
                         if (count1[S[start]] < 0)
                             count1[S[start]]++;
                         else
                             break;
                     }
                     start++;
                 }
             
                 if (minSize > end - start + 1)
                 {
                     minSize = end - start + 1;
                     minStart = start;
                 }
             }
         }
         
         if (minSize == INT_MAX)
             return "";
         
         string ret(S, minStart, minSize);
         
         return ret;        
     }
 };


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值