LeetCode Minimum Window Substring
来源:互联网 发布:淘宝客服数据报表 编辑:程序博客网 时间:2024/06/06 07:02
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.
必须要包含T中所有字符,包括重复的字符。使用数组map记录T中每个字符的个数,数组sum记录S中start--end间的字符个数。定义两个指针start和end,end往后移直到包含所有T中字符,start后压缩,直到不能压缩
判断是否比原来长度小,如果是则更新minstart、minend
end继续往后移,循环
public class Solution { public String minWindow(String S, String T) { int[] map = new int[256];int[] sum = new int[256];int lens = S.length();int lent = T.length();if (lent == 0 || lens == 0 || lent > lens)return "";int res = lens+1;int start = 0, minstart = 0, minend = 0;int num = 0;Arrays.fill(map, 0);Arrays.fill(sum, 0);for (int i = 0; i < lent; i++) { //记录T中字符数map[T.charAt(i)]++;}for (int i = 0; i < lens; i++) { //i即为endif (map[S.charAt(i)] > 0) {sum[S.charAt(i)]++; //记录start--i之间的字符数if (sum[S.charAt(i)] <= map[S.charAt(i)])num++;if (num == lent) { //满足T中的所有字符要求while (start < i) { //压缩startif (map[S.charAt(start)] == 0) { start++;continue;}if (sum[S.charAt(start)] > map[S.charAt(start)]) {sum[S.charAt(start)]--;start++;continue;} elsebreak;}int count = i - start + 1; //计算长度if (count < res) {res = count;minstart = start;minend = i + 1;}}}}return S.substring(minstart, minend); }}
0 0
- 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
- [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
- [LeetCode] Minimum Window Substring
- leetcode minimum window substring
- LeetCode - Minimum Window Substring
- LeetCode:Minimum Window Substring
- 看图说话:11种用户,你如何应对?
- 两分钟彻底让你明白Android Activity生命周期(图文)!
- B树、B-tree B+树、B*树
- tiny6410启动错误
- 第11周项目6-回文、素数-回文素数
- LeetCode Minimum Window Substring
- 安装hadoop1.2集群环境
- 明明已经引入了jquery,还是不断地报错,终于找到原因了
- 在Java中使用weka:产生折叠交叉验证
- ROC曲线-阈值评价标准
- Maven之——仓库(中)
- 数据挖掘在电信欺诈侦测中的应用
- Java SWT Ribbon的使用
- CF - 255C - Almost Arithmetical Progression(dp)