char类型对应整数值范围0~127。
初始化数组应该为:int[] window = new int[128];
滑动窗口Array
class Solution {
public String minWindow ( String s, String t) {
int [ ] window = new int [ 128 ] , need = new int [ 128 ] ;
char [ ] ss = s. toCharArray ( ) , tt = t. toCharArray ( ) ;
int count = 0 , min = ss. length;
String res = "" ;
for ( int i = 0 ; i < tt. length; i++ ) {
need[ tt[ i] ] ++ ;
}
int i = 0 , j = 0 ;
while ( j < ss. length) {
char c = ss[ j] ;
window[ c] ++ ;
if ( window[ c] <= need[ c] ) count++ ;
while ( count == tt. length && i <= j) {
if ( j - i + 1 <= min) {
res = s. substring ( i, j + 1 ) ;
min = j - i + 1 ;
}
window[ ss[ i] ] -- ;
if ( window[ ss[ i] ] < need[ ss[ i] ] ) count-- ;
i++ ;
}
j++ ;
}
return res;
}
}
HashMap
class Solution {
Map< Character, Integer> ori = new HashMap < Character, Integer> ( ) ;
Map< Character, Integer> cnt = new HashMap < Character, Integer> ( ) ;
public String minWindow ( String s, String t) {
int tLen = t. length ( ) ;
for ( int i = 0 ; i < tLen; i++ ) {
ori. put ( t. charAt ( i) , ori. getOrDefault ( t. charAt ( i) , 0 ) + 1 ) ;
}
int l = 0 , r = - 1 ;
int len = Integer. MAX_VALUE, ansL = - 1 , ansR = - 1 ;
int count = 0 ;
int sLen = s. length ( ) ;
while ( r < sLen - 1 ) {
++ r;
if ( ori. containsKey ( s. charAt ( r) ) ) {
cnt. put ( s. charAt ( r) , cnt. getOrDefault ( s. charAt ( r) , 0 ) + 1 ) ;
if ( cnt. get ( s. charAt ( r) ) <= ori. get ( s. charAt ( r) ) ) {
count++ ;
}
}
while ( count == tLen && l <= r) {
if ( r - l + 1 < len) {
len = r - l + 1 ;
ansL = l;
ansR = r + 1 ;
}
if ( ori. containsKey ( s. charAt ( l) ) ) {
cnt. put ( s. charAt ( l) , cnt. getOrDefault ( s. charAt ( l) , 0 ) - 1 ) ;
if ( cnt. get ( s. charAt ( l) ) < ori. get ( s. charAt ( l) ) ) {
count-- ;
}
}
++ l;
}
}
return ansL == - 1 ? "" : s. substring ( ansL, ansR) ;
}
}