Skip to content

Commit ab31d38

Browse files
committed
add leetcode: 76
1 parent 66ddc61 commit ab31d38

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package leetCode.subject.number51_100;
2+
3+
import java.util.HashMap;
4+
5+
/**
6+
* @author : CodeWater
7+
* @create :2022-08-09-23:53
8+
* @Function Description :76. 最小覆盖子串
9+
*/
10+
public class _76MinimumCoverString {
11+
class Solution {
12+
/**滑动窗口/双指针 + 哈希表
13+
用这个方法需要满足的性质:
14+
要有单调性;当第一个指针往前走的时候,第二个指针不能往前后走,导致范围变得更大。
15+
用哈希表统计t中每个字符出现的次数,枚举s的时候就可方便知道ij之间是否满足t。
16+
还有一个哈希表统计窗口内(j,i)每个字符出现的次数,次数count加上之后没有t中字符
17+
出现的次数,那么有效;超过的话,就不统计进去。
18+
通过有效个数count来统计答案
19+
*/
20+
public String minWindow(String s, String t) {
21+
// hs统计窗口内的 ht统计t中的字符
22+
Map<Character , Integer> hs = new HashMap<>() , ht = new HashMap<>();
23+
int count = 0;
24+
String res = "";
25+
26+
// 统计t中的不同字符个数
27+
for( int i = 0 ; i < t.length() ; i++ ){
28+
char c = t.charAt(i);
29+
ht.put( c , ht.containsKey(c) ? ht.get(c) + 1 : 1 );
30+
}
31+
32+
// 双指针遍历s串
33+
for( int i = 0 , j = 0 ; i < s.length() ; i++ ){
34+
char c = s.charAt(i);
35+
// c在hs中有没有,有的话加1,没有就是1
36+
hs.put( c , hs.containsKey(c) ? hs.get(c) + 1 : 1 );
37+
// 判断c是不是有效:在t中,同时窗口内有小于t中的个数
38+
if( ht.containsKey(c) && hs.get(c) <= ht.get(c) ) count++;
39+
//t中不包含j 或者窗口内的j个数大于t中j的个数 -------------这里保证长度最小,如果j字符有多余一直往前走
40+
while( j <= i && ( !ht.containsKey(s.charAt(j) ) || hs.get(s.charAt(j) ) > ht.get( s.charAt(j) ) ) ){
41+
// j添加到窗口中,个数减1,j指针往前走
42+
hs.put( s.charAt(j) , hs.get( s.charAt(j++) ) - 1 );
43+
44+
}
45+
46+
// 当有效个数等于t长度说明找到一种解
47+
if( count == t.length() && (res.length() > (i - j + 1 ) || res.length() < 1 ) ){
48+
// j到i
49+
res = s.substring(j , i + 1 );
50+
}
51+
52+
}
53+
54+
return res;
55+
}
56+
}
57+
}

0 commit comments

Comments
 (0)