使用双指针
class Solution {
public:
string minWindow(string s, string t) {
int m=t.size();
int n=s.size();
int i,j;
unordered_map<char,int> mp;
for(i=0;i<m;i++)
mp[t[i]]++;
unordered_map<char,int> tmp;
int cnt=0;
int sta=0,len=n+1,ind=-1;
for(i=0;i<n;i++)
{
if(mp.find(s[i])!=mp.end())
{
tmp[s[i]]++;
if(tmp[s[i]]<=mp[s[i]])
cnt++;
if(cnt==1)
{
tmp[s[i]]=1;
sta=i;
}
while(cnt==m)
{
if(i-sta+1<len)
{
len=i-sta+1;
ind=sta;
}
tmp[s[sta]]--;
if(tmp[s[sta]]<mp[s[sta]])
cnt--;
sta++;
while(sta<n&&mp.find(s[sta])==mp.end())
sta++;
}
}
}
if(ind!=-1)
return s.substr(ind,len);
return "";
}
};
本文介绍了一种使用双指针技术寻找字符串中包含特定字符集的最短子串的方法。通过维护两个哈希表来跟踪目标字符及其在源字符串中的出现情况,实现了高效的查找过程。
380

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



