import java.io.*;
import java.util.*;
/*
* To execute Java, please define "static void main" on a class
* named Solution.
*
* If you need more classes, simply define them inline.
*/
class Solution {
public String window(String str, Set<Character> set) {
if (set.isEmpty()) return "";
int req = set.size();
HashMap<Character, Integer> map = new HashMap<>();
for (char c : set) {
map.put(c, 0);
}
int s = 0;
int e = 0;
String res = "";
while (true) {
if (req > 0) {
if (e == str.length()) break;
char c = str.charAt(e);
if (map.containsKey(c)) {
if (map.get(c) == 0) req--;
map.put(c, map.get(c) + 1);
}
e++;
}
if (req == 0) {
if (res.isEmpty() || res.length() > e - s) {
res = str.substring(s, e);
}
char c = str.charAt(s);
if (map.containsKey(c)) {
if (map.get(c) == 1) {
req++;
}
map.put(c, map.get(c) - 1);
}
s++;
}
}
return res;
}
public static void main(String[] args) {
Solution s = new Solution();
Set<Character> set = new HashSet<Character>();
set.add('a');
set.add('b');
set.add('c');
System.out.println(s.window("abbcad", set));
}
}
没有评论:
发表评论