From 353fecff332693269da020046f1ce857dfc69d76 Mon Sep 17 00:00:00 2001 From: Bugsource <35368347+Bugsource@users.noreply.github.com> Date: Sun, 18 Aug 2019 19:44:50 +0800 Subject: [PATCH] Create 76. Minimum Window Substring.md --- .../76. Minimum Window Substring.md | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 sliding window/76. Minimum Window Substring.md diff --git a/sliding window/76. Minimum Window Substring.md b/sliding window/76. Minimum Window Substring.md new file mode 100644 index 0000000..2ca4c61 --- /dev/null +++ b/sliding window/76. Minimum Window Substring.md @@ -0,0 +1,56 @@ +# 题目描述 +``` +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). + +Example: + +Input: S = "ADOBECODEBANC", T = "ABC" +Output: "BANC" +Note: + +If there is no such window in S that covers all characters in T, return the empty string "". +If there is such window, you are guaranteed that there will always be only one unique minimum window in S. +``` +# 思路 +1) 关键点在于如何去描述T的窗口,存储出现的字符及个数,最优做法就是用int[256]做map,先存储t里的字符及出现的个数; +2) 右指针遍历S,将map里对应字符的计数减1,如果map里计数为0,则说明T中不存在,将其减为负数;字符个数大于零,则说明在T中存在,增加找到字符的count; +3)如果count等于T的长度,说明窗口匹配成功,此时要移动左指针,尽力去缩短匹配的字符串:将map里计数加1,如果是T中没出现过的,最多加到0;如果是出现过的, +当加到大于0时,说明之前的字符都可以舍弃,此时更新下最短长度; + +# 代码 +``` +class Solution { + public String minWindow(String s, String t) { + int[] window = new int[256]; + int winSize = t.length(); + for(int i = 0; i < winSize; i++){ + window[t.charAt(i)] ++; + } + int left = 0, len = s.length(), count = 0, minLen = Integer.MAX_VALUE, preMinLeft = 0; + for(int right = 0; right < len; right++){ + char c = s.charAt(right); + window[c]--; + if(window[c] >= 0){ + count++; + } + while(count == winSize){//尝试去移动左指针缩小窗口 + char leftChar = s.charAt(left); + window[leftChar]++; + if(window[leftChar] > 0){//t中没有的但是s中有的,最多加到0;大于0的必然是t中有的 + count--; + int curLen = right-left+1; + if(curLen < minLen){//循环跳出时才需要更新下最短长度 + minLen = curLen; + preMinLeft = left; + } + } + left++; + } + } + if(minLen == Integer.MAX_VALUE){ + return ""; + } + return s.substring(preMinLeft, preMinLeft+minLen); + } +} +```