public class Solution {
public String minWindow(String s, String t) {
int min = Integer.MAX_VALUE;
String ret = "";
// assuming all characters are ASCII chars
int[] hash = new int[256];
// count the letter frequency in t
for (char c : t.toCharArray())
hash[c]++;
// set the left and right pointer, set count equals to t.length()
int left = 0, right = 0, count = t.length();
while (right < s.length()) {
// if right points a char that exists in t decrease count
if (hash[s.charAt(right)] > 0)
count--;
// decrease frequency whenever meets a char
hash[s.charAt(right)]--;
right++;
// if count == 0 means we found a solution not necessaryly the minimum
// find the current minimum
while (count == 0) {
// if meets a shorter substring, update the ret string
if (min > right-left) {
min = right-left;
ret = s.substring(left, right);
}
hash[s.charAt(left)]++;
if (hash[s.charAt(left)] > 0) count++;
left++;
}
}
return ret;
}
}
Leetcode 76. Minimum Window Substring
最新推荐文章于 2020-08-17 07:22:22 发布