leetcode 76. Minimum Window Substring
来源:互联网 发布:订餐的软件 编辑:程序博客网 时间:2024/06/05 20:41
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.
题意:
求S串中包含T串的一个最小子串。
思路:
用两个指针st、ed来遍历S串,ed每次走到能包含T串的位置,st再走到刚好不能包含T串的位置,用这两个位置来更新答案。
怎么判断串是否被包含呢,使用num记录T串每个字母出现的次数,共有tot个不同字母,遍历T串的时候也记录字母出现的次数,如果次数和S串中的相等,计数变量cnt++,当cnt=tot的时候,这个子串就能包含T串了。
代码:
class Solution_76 {public: string minWindow(string s, string t) { int n = s.length(), m = t.length(); int nums[256] = {0}; int numt[256] = {0}; for (int i = 0; i < m; ++i) { numt[t[i]]++; } int tot = 0; for (int i = 0; i < 256; ++i) { if (numt[i]) tot++; } if (m == 0) return ""; int cnt = 0, st = 0, ed = 0, best = n + 1, ansst = 0; while (ed < n) { while (ed < n) { nums[s[ed]]++; //printf("%d %d %c\n",nums[s[ed]],numt[s[ed]],s[ed]); if (nums[s[ed]] == numt[s[ed]]) { cnt++; if (cnt == tot) break; } ed++; } //find a qujian if (ed < n) { ed++;// printf("st:%d ed:%d cnt:%d\n",st,ed,cnt); for (; st < ed; st++) {// printf("%d %d %c\n",nums[s[st]],numt[s[st]],s[st]); if (nums[s[st]] == numt[s[st]]) { if (best > ed - st) { best = ed - st; ansst = st; } nums[s[st]]--; st++; cnt--; break; } nums[s[st]]--; }// printf("aft:st:%d ed:%d cnt:%d\n",st,ed,cnt); } } if (best == n + 1) return ""; return s.substr(ansst, best); }};
0 0
- 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
- [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
- 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
- leetcode 76. Minimum Window Substring
- 76. Minimum Window Substring, leetcode
- leetcode-76. Minimum Window Substring
- BZOJ P1041[HAOI2008]圆上的整点
- 设置Ubuntu系统的分辨率--解决vmware workstaion中shell窗口太小的问题
- C语言中运算符的总结
- POJ 1681 画家问题
- 项目实战篇-餐馆管理系统—MFC,PHP,MySql:6.订单管理模块
- leetcode 76. Minimum Window Substring
- xcrun: error: unable to find utility "instruments", not a developer tool or in PATH
- sizeof和strlen的一些用法和区别
- 《黑客与画家》-Paul Graham
- 关于端口被占用
- Java多线程并发处理
- Java并发
- nodejs PM2的使用【陆续整理更新……】
- 515. Find Largest Value in Each Tree Row