[leetcode刷题系列]Minimum Window Substring
2013-08-14 00:38
477 查看
这个也许算是two pointer类型的题目。
先贴一个简单的版本, 这个的复杂度应该算是256 * n
下面的这个是n+256的复杂度,算是
先贴一个简单的版本, 这个的复杂度应该算是256 * n
class Solution{ bool ok(int* a, int * b){ for(int c = 0; c < (1 << 8); ++ c) if(a[c] < b[c]) return false; return true; } public: string minWindow(string S, string T) { // Start typing your C/C++ solution below // DO NOT write int main() function if(S.size() <= 0) return ""; if(T.size() <= 0) return ""; int hash_s[1 << 8] = {0}; int hash_t[1 << 8] = {0}; for(int i = 0; i < T.size(); ++ i) hash_t[T[i]] ++; int st, ans = -1; int p = -1; for(int i = 0; i < S.size(); ++ i){ while(p + 1 < S.size() && !ok(hash_s, hash_t)) if(p + 1< S.size()){ ++ p; hash_s[S[p]] ++ ; }else break; if(ok(hash_s, hash_t)){ if(ans == -1 || p - i + 1 < ans){ ans = p - i + 1; st = i; } } hash_s[S[i]] --; } if(ans == -1) return ""; return S.substr(st, ans); } };
下面的这个是n+256的复杂度,算是
class Solution{ bool ok(int* a, int * b){ for(int c = 0; c < (1 << 8); ++ c) if(a[c] < b[c]) return false; return true; } public: string minWindow(string S, string T) { // Start typing your C/C++ solution below // DO NOT write int main() function if(S.size() <= 0) return ""; if(T.size() <= 0) return ""; int hash_s[1 << 8] = {0}; int hash_t[1 << 8] = {0}; for(int i = 0; i < T.size(); ++ i) hash_t[T[i]] ++; for(int i = 0; i < S.size(); ++ i) hash_s[S[i]] ++ ; if(!ok(hash_s, hash_t)) return ""; int ans = -1, st = 0; int p = S.size() - 1; while(p >= 0){ if(hash_s[S[p]] == hash_t[S[p]]) break; else{ hash_s[S[p]] --; -- p; } } // 0 ans = p + 1; st = 0; for(int i = 1; i < S.size(); ++ i){ char last = S[i - 1]; hash_s[last] --; if(hash_s[last] >= hash_t[last]){ if(ans > p - i + 1){ ans = p - i + 1; st = i; } }else{ bool find = false; while(p + 1 < S.size()){ ++ p; hash_s[S[p]] ++ ; if(S[p] == last){ find = true; break; } } if(!find)break; } } return S.substr(st, ans); } };
相关文章推荐
- LeetCode 笔记系列16.2 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]
- LeetCode 笔记系列16.3 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]
- LeetCode 笔记系列16.1 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]
- **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 76 Minimum Window Substring
- leetCode_Minimum Window Substring
- LeetCode OJ 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 [076]
- LeetCode - Minimum Window Substring
- 【leetcode 76】 Minimum Window Substring