-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinimumWindowSubstring.java
More file actions
68 lines (60 loc) · 2.42 KB
/
Copy pathMinimumWindowSubstring.java
File metadata and controls
68 lines (60 loc) · 2.42 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
61
62
63
64
65
66
67
68
package com.leetcode.year_2020.sliding_window;
import java.util.HashMap;
import java.util.Map;
/**
* https://leetcode.com/problems/minimum-window-substring/
*
* @author neeraj on 17/05/20
* Copyright (c) 2019, data-structures.
* All rights reserved.
*/
public class MinimumWindowSubstring {
public static void main(String[] args) {
System.out.println(minWindow("ADOBECODEBANC", "ABC"));
System.out.println(minWindow("aabcbcdbca", "abcd"));
System.out.println(minWindow("XAYMBAZBDCE", "ABE"));
System.out.println(minWindow("XZYMBEZBDCA", "ABE"));
}
public static String minWindow(String S, String T) {
/**
* This is again a variation of Sliding Window technique.
* and is similar to {@link FindAllAnagramsInAString} problem.
*/
String minWindow = "";
if (T.length() > S.length()) return minWindow;
Map<Character, Integer> charFreq = new HashMap<>();
for (char c : T.toCharArray()) {
charFreq.put(c, charFreq.getOrDefault(c, 0) + 1);
}
// This counter will tell us whether or not window contains
// all characters.
int counter = charFreq.size();
int begin = 0, end = 0;
int minWindowSize = Integer.MAX_VALUE;
while (end < S.length()) {
char charAtEndOfWindow = S.charAt(end);
// Let's expand the window.
if (charFreq.containsKey(charAtEndOfWindow)) {
charFreq.put(charAtEndOfWindow, charFreq.get(charAtEndOfWindow) - 1);
if (charFreq.get(charAtEndOfWindow) == 0) counter--;
}
end++;
// We found a window where all elements of T exist.
// So let's check if this is a min window and just invalidate the window.
// by shrinking it. (i.e. Increment start).
while (counter == 0) {
char charAtStartOfWindow = S.charAt(begin);
if (charFreq.containsKey(charAtStartOfWindow)) {
charFreq.put(charAtStartOfWindow, charFreq.get(charAtStartOfWindow) + 1);
if (charFreq.get(charAtStartOfWindow) > 0) counter++;
}
if (minWindowSize >= (end - begin)) {
minWindowSize = end - begin;
minWindow = S.substring(begin, end);
}
begin++;
}
}
return minWindow;
}
}