2024/9/06 LeetCode Hot100 substring 最后一题之我的解法

This commit is contained in:
Cool 2024-09-06 23:54:54 +08:00
parent de9c5dfa67
commit 0ce86e6903
1 changed files with 44 additions and 22 deletions

View File

@ -1,5 +1,7 @@
package com.cool.hot100.substring;
import org.junit.Test;
import java.util.*;
/**
@ -9,7 +11,7 @@ import java.util.*;
* @Date: 2024/09/06/13:57
* DayNumber 1
* Hard 3
* Level ?
* Level 6
*/
public class Num79 {
@ -17,33 +19,53 @@ public class Num79 {
if (s.length() < t.length()) {
return "";
}
int minLeft=Integer.MIN_VALUE;
int minLeft = 0;
int minRight = Integer.MAX_VALUE;
int left = 0;
int right = 0;
char[] charArray = s.toCharArray();
int index=0;
Map<Character, Integer> tMap = new HashMap<>();
Map<Character, Integer> sMap = new HashMap<>();
for (int i = 0; i < t.length(); i++) {
tMap.put(t.charAt(i),tMap.getOrDefault(i,0)+1);
tMap.put(t.charAt(i), tMap.getOrDefault(t.charAt(i), 0) + 1);
}
for (int i = 0; i < charArray.length; i++) {
if (tMap.containsKey(charArray[i])) {
sMap.put(charArray[i],sMap.get(charArray[i])+1);
if(tMap.get(charArray[i])>sMap.get(charArray[i])){
right++;
}else{
while (sMap.get(charArray[left])>tMap.get(charArray[left])){
sMap.put(charArray[i], sMap.getOrDefault(charArray[i], 0) + 1);
if (tMap.get(charArray[i]) <= sMap.get(charArray[i]) && check(sMap, tMap)) {
while (!tMap.containsKey(charArray[left]) || sMap.getOrDefault(charArray[left], Integer.MAX_VALUE) > tMap.get(charArray[left])) {
if (tMap.containsKey(charArray[left])) {
sMap.put(charArray[left], sMap.get(charArray[left]) - 1);
}
left++;
}
if (right - left < minRight - minLeft) {
minLeft = left;
minRight = right + 1;
}
}
}
right++;
}
return s.substring(left,right);
if (minRight == Integer.MAX_VALUE) {
minLeft = left;
minRight = 0;
}
return s.substring(minLeft, minRight);
}
private boolean check(Map<Character, Integer> sMap, Map<Character, Integer> tMap) {
for (Map.Entry<Character, Integer> next : tMap.entrySet()) {
if (!sMap.containsKey(next.getKey()) || sMap.get(next.getKey()) < next.getValue()) {
return false;
}
}
return true;
}
@Test
public void test() {
System.out.println(minWindow("aa", "aa"));
}
}