904. 水果成篮
滑动窗口,需注意左指针移动时的条件和处理
public int totalFruit(int[] fruits) {
Map<Integer, Integer> basket = new HashMap<>();
int res = -1;
int l = 0;
for (int r = 0; r < fruits.length; r++) {
basket.put(fruits[r], basket.getOrDefault(fruits[r], 0) + 1);
while (basket.size() > 2) {
int leftFruit = fruits[l];
basket.put(leftFruit, basket.get(leftFruit) - 1);
if (basket.get(leftFruit) == 0)
basket.remove(leftFruit);
l++;
}
res = Math.max(res, r - l + 1);
}
return res;
}
76. 最小覆盖子串
离谱,做过的题仿佛没做过LOL
public String minWindow(String s, String t) {
int start = 0;
int end = Integer.MAX_VALUE;
int sLen = s.length();
int tLen = s.length();
if (sLen < tLen)
return "";
Map<Character, Integer> tMap = new HashMap<>();
Map<Character, Integer> sMap = new HashMap<>();
for (char ch : t.toCharArray()) {
tMap.put(ch, tMap.getOrDefault(ch, 0) + 1);
}
int left = 0;
for (int right = 0; right < sLen; right++) {
char ch = s.charAt(right);
sMap.put(ch, sMap.getOrDefault(ch, 0) + 1);
while (find(tMap, sMap)) {
char leftLetter = s.charAt(left);
if ((right - left) < (end - start)) {
start = left;
end = right;
}
sMap.put(leftLetter, sMap.get(leftLetter) - 1);
if (sMap.get(leftLetter) == 0)
sMap.remove(leftLetter);
left++;
}
}
return s.substring(start, end + 1);
}
public Boolean find(Map<Character, Integer> tMap, Map<Character, Integer> sMap) {
Set<Character> keySet = tMap.keySet();
for (Character key : keySet) {
if (sMap.get(key) == null || tMap.get(key) > sMap.get(key))
return false;
}
return true;
}
public String minWindow(String s, String t) {
Map<Character, Integer> count = new HashMap<>();
for (char ch : t.toCharArray())
count.merge(ch, 1, Integer::sum);
int l = 0;
int minLen = s.length() + 1;
int start = 0;
int haveSame = 0;
for (int r = 0; r < s.length(); r++) {
char current = s.charAt(r);
if (count.containsKey(current)) {
count.put(current, count.get(current) - 1);
if (count.get(current) == 0)
haveSame++;
}
while (haveSame == count.size()) {
if (minLen > (r - l + 1)) {
start = l;
minLen = r - l + 1;
}
char leftChar = s.charAt(l++);
if (count.containsKey(leftChar)) {
if (count.get(leftChar) == 0)
haveSame--;
count.put(leftChar, count.get(leftChar) + 1);
}
}
}
return minLen > s.length() ? "" : s.substring(start, start + minLen);
}