-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterview10.java
More file actions
43 lines (39 loc) · 1015 Bytes
/
Interview10.java
File metadata and controls
43 lines (39 loc) · 1015 Bytes
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
package pramp;
/**
* Given a string and a character set, return the shortest substring that
* contains all the characters.
*
* @author: shivam.maharshi
*/
public class Interview10 {
public static String get(String s, char[] a) {
if (a == null || a.length == 0 || s == null || s.length() == 0 || a.length > s.length())
return null;
String r = null;
int[] c = new int[256];
for (int i = 0; i < a.length; i++)
c[s.charAt(i)]++;
int i = 0, j = a.length - 1;
while (i <= s.length() - a.length && j <= s.length()) {
if (allPresent(a, c)) {
r = (r == null || r.length() > j - i) ? s.substring(i, j) : r; // 5, 8
if (r.length() == a.length)
return r;
c[s.charAt(i)]--;
i++;
} else {
j++;
c[s.charAt(j)]++;
}
}
return r;
}
public static boolean allPresent(char[] a, int[] c) {
for (char aa : a) {
if (c[aa] == 0)
return false;
c[aa]--;
}
return true;
}
}