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);
}
}
这是我的一个Leetcode问题的代码。但我不认为它涉及算法问题。所以我把它张贴在这里。这里是问题:
我使用散列表“记录”来记录S中重复的字符和另一个“set”来记录T中重复的字符。当重复的字符数相等时,加上一个变量“计数”;
我通过了所有试验除了最后一个S为长度100000的字符串和T是具有长度10001
字符串我必须使用这种形式:
有人可以看到为什么在这里两个“整数”不能比较?
int num1 = record.get(tmp);
int num2 = set.get(tmp);
if (num1 == num2) {
count++;
}
代替:
if(record.get(tmp)==set.get(tmp)){
count++;
}
只有这样才能将两个整数进行比较或不计算“计数”。为什么前265个测试用例可以通过,但最后一个大字符串会导致问题?先谢谢你。
@deathlee,你的问题得到解决了吗? –