leetcode: Minimum Window Substring
2014-12-06 16:11
169 查看
同时请参阅 :http://blog.csdn.net/martin_liang/article/details/8592894
相同的问题,解法稍微有一点不一样
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.
相同的问题,解法稍微有一点不一样
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.
class Solution { public: string minWindow(string S, string T) { map<char, int> matchingMap; for (int i=0; i<T.size(); i++) { if (matchingMap.find(T.at(i)) == matchingMap.end()) { matchingMap[T.at(i)] = 1; } else { matchingMap[T.at(i)]++; } } map<char, int> loopingMap; int count = 0; int startPos = 0; int minLen = S.size(); string retString; for (int i=0; i<S.size(); i++) { if (matchingMap.find(S.at(i)) != matchingMap.end()) { if (loopingMap.find(S.at(i)) == loopingMap.end()) { loopingMap[S.at(i)] = 1; } else { loopingMap[S.at(i)]++; } if (loopingMap[S.at(i)] <= matchingMap[S.at(i)]) count++; // example T:ABC S: AAABC, 当遇到第二和第三个A时,count都不会加一,最终要进行match的时候,count必定为3 if (count == T.size()) { while (true) // 注意这里的循环 { if (matchingMap.find(S.at(startPos)) == matchingMap.end()) { startPos++; continue; } if (loopingMap[S.at(startPos)] > matchingMap[S.at(startPos)]) { loopingMap[S.at(startPos)]--; startPos++; } else { break; } } if (i-startPos+1 <= minLen) { minLen = i-startPos+1; retString = S.substr(startPos, minLen); } count--; loopingMap[S.at(startPos)]--; startPos++; } } } return retString; } };
相关文章推荐
- LeetCode – Refresh – 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
- LeetCode - Minimum Window Substring
- Minimum Window Substring 最小子串窗口@LeetCode
- LeetCode-Minimum Window Substring -- 窗口问题
- LeetCode: Minimum Window Substring
- leetcode——Minimum Window Substring
- LeetCode: 76. Minimum Window Substring
- Leetcode231: Minimum Window Substring
- [Leetcode] minimum window substring 最小字符窗口
- LeetCode76 Minimum Window Substring(两种解法)
- leetcode76题 Minimum Window Substring
- leetcode解题笔记-Minimum Window Substring
- 【LeetCode】Minimum Window Substring