-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
60 lines (56 loc) · 1.97 KB
/
Solution.java
File metadata and controls
60 lines (56 loc) · 1.97 KB
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
//Justin Butler
//11/9/2021
/*
Runtime: 12 ms
Memory Usage: 39.5 MB
Beats 60% of Java Submissions.
*/
class Solution {
public String minWindow(String s, String t)
{
HashMap<Character, Integer> target = new HashMap<>();
if(s.equals(t)){return t;} // handle edge cases
if(s.isEmpty() || t.isEmpty()){return "";}
//1. We will map the target chars that need to be in our substring.
for(int i = 0; i < t.length(); i++)
{
char ch = t.charAt(i);
if(target.containsKey(ch))
{target.put(ch, target.get(ch)+1);}
else
{target.put(ch, 1);}
}
// Set up for out sliding window.
// count starts out at target size, when it = 0, we know it is a matching substring.
// int left and int right will hold the location indexes of the current smallest substring.
int i = 0, j = 0, count = target.size();
int left = 0, right = s.length()-1, min =s.length();
boolean found = false; // for our return statement.
while(j < s.length())
{
char lastChar = s.charAt(j++);
if(target.containsKey(lastChar))
{
target.put(lastChar, target.get(lastChar)-1);
if(target.get(lastChar)==0){count-=1;}
}
if(count >0) continue;
while(count ==0){
char startChar = s.charAt(i++);
if(target.containsKey(startChar))
{
target.put(startChar, target.get(startChar)+1);
if(target.get(startChar)>0){count+=1;}
}
}
if((j-i)<min) // check if current substring is smaller than our known min.
{
left = i;
right = j;
min = j-i;
found = true;
}
}
return found ? s.substring(left-1, right) : "";
}
}