国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

76. Minimum Window Substring

2019-11-08 03:20:11
字體:
來源:轉載
供稿:網友

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 empty string"".

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

Subscribe to see which companies asked this question.

給出了;兩個字符串s和t,求s中包含t所有字符的最短的子字符串。要注意的是t中的字符可能是重復的。這里使用兩個索引left和right指定符合條件的子字符串的開頭和結尾。首先對right自增,直到t中的所有字符都有了。因為有重復的字符,所以用map來記錄好重復次數,當所有次數都滿足時停止right的增長。現在s[left, right]已經是符合要求的子字符串。為了求最短的,將left增長,直到剛好有一個字符的數量不滿足次數要求,現在的s[left, right]就是當前最短的答案。然后又將right增長,求另外的有可能的答案。。。最后返回最短的答案即可。

代碼:

class Solution{public:	string minWindow(string s, string t) 	{		int cnt[256] = {0}, map[256] = {0};		int types = 0, left = 0, right = 0, n = 0, len = INT_MAX;		string res;		for(auto c:t) 		{			if(map[c]++ == 0) n++;		}		while(right < s.size())		{			while(right < s.size() && types < n)			{				if(map[s[right]] > 0 && ++cnt[s[right]] == map[s[right]])				{					++types;				}				++right;			}			if(types < n) break;			while(left < right)			{				if(map[s[left]] > 0 && --cnt[s[left]] < map[s[left]])				{					--types;					break;				}				++left;			}			if(right - left < len)			{				len = right - left;				res = s.substr(left, right-left);			}			++left;		}		return res;	}};

在別人的答案中看到一個號稱是最短的答案,挺不錯的:

string minWindow(string s, string t) {        vector<int> map(128,0);        for(auto c: t) map[c]++;        int counter=t.size(), begin=0, end=0, d=INT_MAX, head=0;        while(end<s.size()){            if(map[s[end++]]-->0) counter--; //in t            while(counter==0){ //valid                if(end-begin<d)  d=end-(head=begin);                if(map[s[begin++]]++==0) counter++;  //make it invalid            }          }        return d==INT_MAX? "":s.substr(head, d);    }


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 林西县| 商河县| 瓮安县| 武平县| 龙南县| 江都市| 通榆县| 太康县| 芮城县| 疏勒县| 汉川市| 温州市| 文昌市| 永胜县| 深泽县| 庆阳市| 横山县| 黄龙县| 新野县| 芜湖县| 特克斯县| 中山市| 银川市| 明溪县| 新和县| 光山县| 郧西县| 高要市| 清远市| 许昌县| 晴隆县| 遵义市| 梁山县| 巴东县| 龙山县| 襄汾县| 新郑市| 辰溪县| 雷州市| 奉节县| 视频|