本文主要是介绍leetcode -- 76. Minimum Window Substring,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目描述
题目难度:Hard
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.
AC代码
值得反复揣摩的一段代码。
class Solution {public String minWindow(String s, String t) {int sLen = s.length(), tLen = t.length(), count = t.length(), start = 0, minLen = Integer.MAX_VALUE;int[] freq = new int[128];char[] sc = s.toCharArray();char[] tc = t.toCharArray();for(char c: tc) {freq[c]++;}int l=0,r=0;while(r<sLen) {if(freq[sc[r++]]-- > 0) {count--;}while(count == 0) {if(minLen > r-l) {minLen = r-l;start = l;}if(freq[sc[l++]]++ == 0)count++;}}return minLen == Integer.MAX_VALUE ? "" : s.substring(start,start+minLen);}
}
这篇关于leetcode -- 76. Minimum Window Substring的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!