展会信息港展会大全

leetcode:Minimum Window Substring(最小覆盖子串)【面试算法题】
来源:互联网   发布日期:2015-09-26 22:30:29   浏览:2320次  

导读:题目: 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 c...

题目:

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.

题意就是在S中选一个最小的子串,使得包含T中所有的字母。

做法就是双指针的贪心做法,找到以i结尾的最小子串满足条件。

minn和left,right分别记录最小子串的最小值和左右位置。

data存T串的信息,now存当前i到j的信息,保存的是元素的个数。

num记录增加的元素个数是否达到条件。

class Solution {

public:

string minWindow(string S, string T) {

int data[260],i,j;

memset(data,0,sizeof(data));

for(i=0;i<T.length();++i)

data[T[i]]++;

int now[260],left,right,minn=1<<29,num=0;

memset(now,0,sizeof(now));

for(i=0,j=0;i<S.length();++i)

{

if(num<T.length())

{

if(now[S[i]]<data[S[i]])num++;

now[S[i]]++;

}

if(num==T.length())

{

while(j<=i&&now[S[j]]-1>=data[S[j]])

{

--now[S[j]];

++j;

}

if(minn>i-j+1)left=j,right=i,minn=i-j+1;

while(j<=i&&num==T.length())

{

now[S[j]]--;

if(now[S[j]]<data[S[j]])num--;

++j;

}

}

}

string temp;

if(minn<1<<29)return temp.assign(S,left,right-left+1);

else return "";

}

};

赞助本站

人工智能实验室

相关热词: cocos2d 游戏开发 教程

AiLab云推荐
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港