@@ -17,7 +17,7 @@ public static void main(String[] args) {
17
17
}
18
18
public static String minWindow (String s , String t ) {
19
19
HashMap <Character ,Integer > mp = new HashMap ();
20
- for (int i = 0 ; i < t .length () ; i ++) { //统计每个字符出现的个数
20
+ for (int i = 0 ; i < t .length () ; i ++) { // 统计每个字符出现的个数
21
21
char ch = t .charAt (i );
22
22
if (mp .containsKey (ch ))
23
23
mp .put (ch ,mp .get (ch )+1 );
@@ -37,7 +37,7 @@ public static String minWindow(String s, String t) {
37
37
if (mp .get (ch_r )>=0 ) // <0说明重复了
38
38
count ++;
39
39
}
40
- while (count ==t .length ()){//右移左指针
40
+ while (count ==t .length ()){//右移左指针,注意这个判定条件
41
41
if (right -left +1 <res_len ){ //更新结果
42
42
res_left = left ;
43
43
res_len = right -left +1 ;
@@ -56,4 +56,39 @@ public static String minWindow(String s, String t) {
56
56
return "" ;
57
57
return s .substring (res_left ,res_left +res_len );
58
58
}
59
+
60
+ public String minWindow2 (String s , String t ) {
61
+ HashMap <Character , Integer > hm = new HashMap ();
62
+ char [] t_arr = t .toCharArray ();
63
+ for (int i =0 ; i <t_arr .length ; i ++){
64
+ hm .put (t_arr [i ], hm .getOrDefault (t_arr [i ], 0 )+1 );
65
+ }
66
+ int left = 0 ;
67
+ int right = 0 ;
68
+ int count = t .length ();
69
+ char [] s_arr = s .toCharArray ();
70
+ int res = Integer .MAX_VALUE ;
71
+ int res_left = 0 ;
72
+ int res_right = 0 ;
73
+ while (right <s .length ()){ //一共两个while
74
+ if (hm .containsKey (s_arr [right ])){
75
+ hm .put (s_arr [right ], hm .get (s_arr [right ])-1 );
76
+ if (hm .get (s_arr [right ])>=0 ) count --; //别忘了这一层的判断
77
+ }
78
+ right ++; //在if外边
79
+ while (count ==0 ){ //注意判断条件
80
+ if (right -left +1 <res ){ //记录结果
81
+ res = right -left +1 ;
82
+ res_left = left ;
83
+ res_right = right ;
84
+ }
85
+ if (hm .containsKey (s_arr [left ])){
86
+ hm .put (s_arr [left ], hm .get (s_arr [left ])+1 );
87
+ if (hm .get (s_arr [left ])>0 ) count ++;
88
+ }
89
+ left ++;
90
+ }
91
+ }
92
+ return s .substring (res_left , res_right );
93
+ }
59
94
}
0 commit comments