forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_76.java
85 lines (77 loc) · 2.51 KB
/
_76.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package com.fishercoder.solutions;
public class _76 {
public static class Solution1 {
public String minWindow(String s, String t) {
int[] counts = new int[256];
for (char c : t.toCharArray()) {
counts[c]++;
}
int start = 0;
int end = 0;
int minStart = 0;
int minLen = Integer.MAX_VALUE;
int counter = t.length();
while (end < s.length()) {
if (counts[s.charAt(end)] > 0) {
counter--;
}
counts[s.charAt(end)]--;
end++;
while (counter == 0) {
if (end - start < minLen) {
minStart = start;
minLen = end - start;
}
counts[s.charAt(start)]++;
if (counts[s.charAt(start)] > 0) {
counter++;
}
start++;
}
}
if (minLen == Integer.MAX_VALUE) {
return "";
}
return s.substring(minStart, minStart + minLen);
}
}
public static class Solution2 {
/**
* I implemented below solution on my own following the hints on LeetCode.
* In comparison, Solution1 is more optimized and runs faster.
*/
public String minWindow(String s, String t) {
if (t.length() > s.length()) {
return "";
}
int[] tCount = new int[256];
for (int i = 0; i < t.length(); i++) {
tCount[t.charAt(i)]++;
}
int left = 0;
int right = 0;
int[] sCount = new int[256];
String ans = "";
while (right < s.length()) {
sCount[s.charAt(right)]++;
while (isValid(sCount, tCount)) {
if (right - left < ans.length() || ans.equals("")) {
ans = s.substring(left, right + 1);
}
sCount[s.charAt(left)]--;
left++;
}
right++;
}
return ans;
}
private boolean isValid(int[] sCount, int[] tCount) {
for (int i = 0; i < sCount.length; i++) {
if (sCount[i] < tCount[i]) {
return false;
}
}
return true;
}
}
}