File tree Expand file tree Collapse file tree 1 file changed +76
-0
lines changed Expand file tree Collapse file tree 1 file changed +76
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * @lc app=leetcode.cn id=76 lang=java
3
+ *
4
+ * [76] 最小覆盖子串
5
+ *
6
+ * https://leetcode-cn.com/problems/minimum-window-substring/description/
7
+ *
8
+ * algorithms
9
+ * Hard (37.77%)
10
+ * Likes: 636
11
+ * Dislikes: 0
12
+ * Total Accepted: 61.7K
13
+ * Total Submissions: 161.6K
14
+ * Testcase Example: '"ADOBECODEBANC"\n"ABC"'
15
+ *
16
+ * 给你一个字符串 S、一个字符串 T,请在字符串 S 里面找出:包含 T 所有字符的最小子串。
17
+ *
18
+ * 示例:
19
+ *
20
+ * 输入: S = "ADOBECODEBANC", T = "ABC"
21
+ * 输出: "BANC"
22
+ *
23
+ * 说明:
24
+ *
25
+ *
26
+ * 如果 S 中不存这样的子串,则返回空字符串 ""。
27
+ * 如果 S 中存在这样的子串,我们保证它是唯一的答案。
28
+ *
29
+ *
30
+ */
31
+
32
+ // @lc code=start
33
+ class Solution {
34
+ public String minWindow (String s , String t ) {
35
+ int [] need = new int [128 ];
36
+ int [] window = new int [128 ];
37
+ for (char ch : t .toCharArray ()) {
38
+ need [ch ]++;
39
+ }
40
+
41
+ int left = 0 , right = 0 ;
42
+ int count = 0 ;
43
+ int start = 0 , len = s .length () + 1 ;
44
+
45
+ while (right < s .length ()) {
46
+ char ch = s .charAt (right );
47
+ right ++;
48
+ if (need [ch ] > 0 ) {
49
+ window [ch ]++;
50
+ if (window [ch ] <= need [ch ]) {
51
+ count ++;
52
+ }
53
+ }
54
+
55
+ while (count == t .length ()) {
56
+ if (right - left < len ) {
57
+ start = left ;
58
+ len = right - left ;
59
+ }
60
+
61
+ ch = s .charAt (left );
62
+ left ++;
63
+ if (need [ch ] > 0 ) {
64
+ if (window [ch ] <= need [ch ]) {
65
+ count --;
66
+ }
67
+ window [ch ]--;
68
+ }
69
+ }
70
+ }
71
+
72
+ return (len > s .length ()) ? "" : s .substring (start , start + len );
73
+ }
74
+ }
75
+ // @lc code=end
76
+
You can’t perform that action at this time.
0 commit comments