LeetCode-Minimum Window Substring
2014-08-09 23:36
441 查看
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 emtpy string
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
Solution:
Code:
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.
Solution:
Code:
<span style="font-size:14px;">class Solution { public: string minWindow(string S, string T) { int lengthS = S.size(), lengthT = T.size(); if (lengthT > lengthS) return ""; unordered_map<char, int> hashTable; for (int i = 0; i < lengthT; i++) hashTable[T[i]]++; int count = 0, begin = 0, end = 0; for (; end < lengthS; end++) if (hashTable.find(S[end]) != hashTable.end()) { hashTable[S[end]]--; if (hashTable[S[end]] >= 0) count++; if (count == lengthT) break; } if (count != lengthT) return ""; for (; begin <= end; begin++) if (hashTable.find(S[begin]) == hashTable.end()) continue; else if (hashTable[S[begin]] < 0) hashTable[S[begin]]++; else if (hashTable[S[begin]] == 0) break; int minLength = end-begin+1; int result = begin; end++; for (; end < lengthS; end++) if (S[begin] == S[end]) { begin++; for (; begin <= end; begin++) if (hashTable.find(S[begin]) == hashTable.end()) continue; else if (hashTable[S[begin]] < 0) hashTable[S[begin]]++; else if (hashTable[S[begin]] == 0) break; if (end-begin+1 < minLength) { minLength = end-begin+1; result = begin; } } else { if (hashTable.find(S[end]) != hashTable.end()) hashTable[S[end]]--; } return S.substr(result, minLength); } };</span>
相关文章推荐
- LeetCode 笔记系列16.2 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]
- Minimum Window Substring leetcode java
- LeetCode -- Minimum Window Substring
- leetcode — minimum-window-substring
- LeetCode 76 Minimum Window Substring
- 【LeetCode】 Minimum Window Substring
- LeetCode-Minimum Window Substring
- LeetCode Minimum Window Substring
- LeetCode-Minimum Window Substring
- LeetCode: Minimum Window Substring
- leetcode第一刷_Minimum Window Substring
- LeetCode76 Minimum Window Substring(两种解法)
- LeetCode Minimum Window Substring
- Leetcode_minimum-window-substring(c++ version)
- Minimum Window Substring(leetcode)
- leetcode:Minimum Window Substring 细致分析
- Leetcode:Minimum Window Substring
- leetcode 76 Minimum Window Substring
- Minimum Window Substring @LeetCode
- LeetCode Minimum Window Substring