|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 |
| -/** |
4 |
| - * 76. Minimum Window Substring |
5 |
| - * |
6 |
| - * Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). |
7 |
| -
|
8 |
| - For example, |
9 |
| - S = "ADOBECODEBANC" |
10 |
| - T = "ABC" |
11 |
| -
|
12 |
| - Minimum window is "BANC". |
13 |
| -
|
14 |
| - Note: |
15 |
| -
|
16 |
| - If there is no such window in S that covers all characters in T, return the empty string "". |
17 |
| - If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S. |
18 |
| - */ |
19 |
| - |
20 | 3 | public class _76 {
|
21 | 4 |
|
22 |
| - public static class Solution1 { |
23 |
| - public String minWindow(String s, String t) { |
24 |
| - int[] counts = new int[256]; |
25 |
| - for (char c : t.toCharArray()) { |
26 |
| - counts[c]++; |
27 |
| - } |
28 |
| - |
29 |
| - int start = 0; |
30 |
| - int end = 0; |
31 |
| - int minStart = 0; |
32 |
| - int minLen = Integer.MAX_VALUE; |
33 |
| - int counter = t.length(); |
34 |
| - while (end < s.length()) { |
35 |
| - if (counts[s.charAt(end)] > 0) { |
36 |
| - counter--; |
| 5 | + public static class Solution1 { |
| 6 | + public String minWindow(String s, String t) { |
| 7 | + int[] counts = new int[256]; |
| 8 | + for (char c : t.toCharArray()) { |
| 9 | + counts[c]++; |
| 10 | + } |
| 11 | + |
| 12 | + int start = 0; |
| 13 | + int end = 0; |
| 14 | + int minStart = 0; |
| 15 | + int minLen = Integer.MAX_VALUE; |
| 16 | + int counter = t.length(); |
| 17 | + while (end < s.length()) { |
| 18 | + if (counts[s.charAt(end)] > 0) { |
| 19 | + counter--; |
| 20 | + } |
| 21 | + |
| 22 | + counts[s.charAt(end)]--; |
| 23 | + end++; |
| 24 | + |
| 25 | + while (counter == 0) { |
| 26 | + if (end - start < minLen) { |
| 27 | + minStart = start; |
| 28 | + minLen = end - start; |
| 29 | + } |
| 30 | + counts[s.charAt(start)]++; |
| 31 | + if (counts[s.charAt(start)] > 0) { |
| 32 | + counter++; |
| 33 | + } |
| 34 | + start++; |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + if (minLen == Integer.MAX_VALUE) { |
| 39 | + return ""; |
| 40 | + } |
| 41 | + return s.substring(minStart, minStart + minLen); |
37 | 42 | }
|
38 |
| - |
39 |
| - counts[s.charAt(end)]--; |
40 |
| - end++; |
41 |
| - |
42 |
| - while (counter == 0) { |
43 |
| - if (end - start < minLen) { |
44 |
| - minStart = start; |
45 |
| - minLen = end - start; |
46 |
| - } |
47 |
| - counts[s.charAt(start)]++; |
48 |
| - if (counts[s.charAt(start)] > 0) { |
49 |
| - counter++; |
50 |
| - } |
51 |
| - start++; |
52 |
| - } |
53 |
| - } |
54 |
| - |
55 |
| - if (minLen == Integer.MAX_VALUE) { |
56 |
| - return ""; |
57 |
| - } |
58 |
| - return s.substring(minStart, minStart + minLen); |
59 | 43 | }
|
60 |
| - } |
61 | 44 | }
|
0 commit comments