Leetcode 76 Minimum Window Substring
2016-09-23 10:19
239 查看
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 =
T =
Minimum window is
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.
找出包含给定串所有字符的最小子串
两个指针向后滑,用map记录出现字符的次数。
class Solution {
public:
string minWindow(string s, string t)
{
int maxlen=INT_MAX;
string result;
unordered_map<char,int> mp,mp2;
int cnt=t.size();
for(int i=0;i<cnt;i++) mp[t[i]]++;
for(int st=0,en=0;en<s.size();en++)
{
if(mp[s[en]]>0 )
{
mp2[s[en]]++;
if(mp2[s[en]]<=mp[s[en]]) cnt--;
}
if(cnt==0)
{
while((mp2[s[st]]==0 || mp2[s[st]]>mp[s[st]]) && st<=en)
{
if(mp2[s[st]]>mp[s[st]]) mp2[s[st]]--;
st++;
}
if(en-st+1<maxlen)
{
maxlen=en-st+1;
result=s.substr(st,en-st+1);
}
cnt++;
mp2[s[st]]--;
st++;
}
}
return result;
}
};
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.
找出包含给定串所有字符的最小子串
两个指针向后滑,用map记录出现字符的次数。
class Solution {
public:
string minWindow(string s, string t)
{
int maxlen=INT_MAX;
string result;
unordered_map<char,int> mp,mp2;
int cnt=t.size();
for(int i=0;i<cnt;i++) mp[t[i]]++;
for(int st=0,en=0;en<s.size();en++)
{
if(mp[s[en]]>0 )
{
mp2[s[en]]++;
if(mp2[s[en]]<=mp[s[en]]) cnt--;
}
if(cnt==0)
{
while((mp2[s[st]]==0 || mp2[s[st]]>mp[s[st]]) && st<=en)
{
if(mp2[s[st]]>mp[s[st]]) mp2[s[st]]--;
st++;
}
if(en-st+1<maxlen)
{
maxlen=en-st+1;
result=s.substr(st,en-st+1);
}
cnt++;
mp2[s[st]]--;
st++;
}
}
return result;
}
};
相关文章推荐
- LeetCode76 Minimum Window Substring(两种解法)
- LeetCode76 Minimum Window Substring(两种解法)
- LeetCode 76 Minimum Window Substring
- LeetCode76 Minimum Window Substring(两种解法)
- leetcode 76 Minimum Window Substring/ 209 Minimum Size Subarray Sum
- leetcode 76: Minimum Window Substring
- LeetCode 76 Minimum Window Substring
- LeetCode(76) Minimum Window Substring
- LeetCode76——Minimum Window Substring
- LeetCode: 76. Minimum Window Substring
- LeetCode76 Minimum Window Substring
- Leetcode 76-MinimumWindowSubstring 解题报告
- LeetCode(76) Minimum Window Substring
- [leetcode 76] Minimum Window Substring
- leetcode[76] Minimum Window Substring
- [leetcode] 76 Minimum Window Substring
- LeetCode(76)Minimum Window Substring
- leetcode76题 Minimum Window Substring
- leetcode-76 Minimum Window Substring
- leetcode 76: Minimum Window Substring