public String minWindow(String S, String T) {
if (T.length() > S.length())
return "";
HashMap<Character, Integer> set = new HashMap<>();
for (int i = 0; i < T.length(); i++) {
if (!set.containsKey(T.charAt(i))) {
set.put(T.charAt(i), 1);
} else {
set.put(T.charAt(i), set.get(T.charAt(i)) + 1);
}
}
int count = 0;
int min = Integer.MAX_VALUE;
int begin = 0;
int end = 0;
LinkedList<Integer> index = new LinkedList<>();
HashMap<Character, Integer> record = new HashMap<>();
for (int i = 0; i < S.length(); i++) {
Character tmp = S.charAt(i);
if (set.containsKey(tmp)) {
index.add(i);
if (record.containsKey(tmp)) {
record.put(tmp, record.get(tmp) + 1);
} else {
record.put(tmp, 1);
}
int num1 = record.get(tmp);
int num2 = set.get(tmp);
if (num1 == num2) {
count++;
}
if (count == set.size()) {
Character head = S.charAt(index.peek());
while (record.get(head) > set.get(head)) {
record.put(head, record.get(head) - 1);
index.remove();
head = S.charAt(index.peek());
}
if (index.getLast() - index.peek() < min) {
min = index.getLast() - index.peek();
begin = index.peek();
end = index.getLast();
}
}
} else {
continue;
}
}
if (min == Integer.MAX_VALUE) {
return "";
} else {
return S.substring(begin, end + 1);
}
}
This is the my code of one Leetcode problem. But I don't think it involves the algorithm problem. So I post it here. Here it is the problem:
I use a hashmap "record" to record the duplicated characters in S and another one "set" to record the duplicated characters in T. When the number of the duplicated characters equal, plus one to variable "count";
I passed all the test except the last one S is a string of length 100000 and T is a string with length 10001.
I must use this form:
int num1 = record.get(tmp);
int num2 = set.get(tmp);
if (num1 == num2) {
count++;
}
instead of:
if(record.get(tmp)==set.get(tmp)){
count++;
}
Only like this can the two integers be compared or the "count" won't be plused. Why the first 265 test cases can pass but the last large string causes the problem? Thank you in advance.