【LeetCode 76】 Minimum Window Substring
2017-03-01 22:16
465 查看
/****************************** LeetCode 76. Minimum Window Substring 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. ******************************/ /************************ 思想: 1.遍历t字符,构建hash表,此处可以用数组hashmap[256]实现 2.初始化hashmap数组为-65536:原因是用数组同时记录t中出现的字符以及个数 3.遍历字符串s,定义一个变量count,记录t中字符已经出现的个数 4.count==0时表示所有字符都出现 5.考虑的问题 字符串t中具有重复字符 *************************/ string minWindow(string s, string t) {
if (t.size() < 1 || s.size() < 1) return ""; int hashmap[256]; memset(hashmap,-10,sizeof(hashmap)); for (int ii = 0; ii < 256; ii++) { hashmap[ii] = -65536; } int size = t.size(); for (int ii = 0; ii < size; ++ii) { if (hashmap[t[ii]] == -65536) hashmap[t[ii]] = 1; else hashmap[t[ii]] += 1; } int l = 0; while (l<s.size() &&hashmap[s[l]]==-65536) { l++;//找到在t中的第一个字符 } size = s.size(); if (l == size) return ""; int minLen = 65535; int count = t.size(); string minWindow=""; for (int ii = l; ii < size; ii++) { if (count > 0) { if (hashmap[s[ii]] > 0)//说明t中包含s[r],考虑到t中有重复字符 !=0判断个数没有达到要求 { count--; hashmap[s[ii]] -= 1; } else if (hashmap[s[ii]]!=-65536)//说明t中包含s[r],考虑到t中有重复字符 !=0判断个数已经达到要求 { hashmap[s[ii]] -= 1; } if (count==0 && (ii - l +1 < minLen)) { while(hashmap[s[l]] < 0) { hashmap[s[l]] += 1; l++; } minLen = ii - l +1; minWindow = s.substr(l, minLen); } } else//找到包含所有字符的字符串了 { if (s[ii] == s[l] ) { l++; while ( hashmap[s[l]]<0) { if (hashmap[s[l]] != -65536) { hashmap[s[l]] += 1; } l++; } } else { if (hashmap[s[ii]] != -65536) { hashmap[s[ii]] -= 1; } } if (ii - l+1 < minLen) { minLen = ii - l+1 ; minWindow = s.substr(l, minLen); } } } return minWindow;}
相关文章推荐
- LeetCode(76)Minimum Window Substring
- leetcode-76 Minimum Window Substring
- LeetCode76 Minimum Window Substring(两种解法)
- LeetCode 76: Minimum Window Substring
- LeetCode_OJ【76】Minimum Window Substring
- LeetCode-76-Minimum Window Substring 尺取法+字典
- Leetcode-76 Minimum Window Substring
- leetcode hard模式专杀之76 Minimum Window Substring
- LeetCode 76 Minimum Window Substring
- LeetCode76 Minimum Window Substring(两种解法)
- Leetcode 76-MinimumWindowSubstring 解题报告
- leetcode 76 Minimum Window Substring/ 209 Minimum Size Subarray Sum
- leetcode 76:Minimum Window Substring
- [leetcode-76]Minimum Window Substring(java)
- Leetcode 76 Minimum Window Substring(最小窗口的子串)
- LeetCode76 Minimum Window Substring(两种解法)
- leetcode 76: Minimum Window Substring
- leetcode[76] Minimum Window Substring
- LeetCode 76 Minimum Window Substring
- LeetCode: 76. Minimum Window Substring