leetcode76——Minimum Window Substring

题目大意:在字符串s中找出最短子串,使他包含字符串t中的所有字符(可以不按t中字符顺序,只要包含即可)

分析:哈希表、字符串考察。滑动窗口方法。将字符串t中的字符储存在哈希表中,遍历字符串s,用left和right指针维持滑动窗口左右界限,right右滑找到在t中存在的字符,该字符对应的哈希值减一,如果滑动窗口中找到的字符数量和t的长度相等就说明找到了一个答案,更新即可。

代码:JAVA转载自https://blog.csdn.net/u013115610/article/details/70257445

public static String minWindow(String s, String t) {
Map<Character, Integer> map = new HashMap<>();
int min = Integer.MAX_VALUE;
int minStart = 0, minEnd = 0;
int count = t.length();
for (char c : t.toCharArray()) {
map.put(c, map.containsKey(c) ? map.get(c) + 1 : 1);
}
int left = 0;
for (int right = 0; right < s.length(); right++) {
char val = s.charAt(right);
if (map.containsKey(val)) {
map.put(val, map.get(val) - 1);
if (map.get(val) >= 0) {
count--;
}
}
while (count == 0) {
if (right - left < min) {
min = right - left;
minStart = left;
minEnd = right;
}
char temp = s.charAt(left);
if (map.containsKey(temp)) {
map.put(temp, map.get(temp) + 1);
if (map.get(temp) > 0) count++;
}
left++;
}
}
return min == Integer.MAX_VALUE ? "" : s.substring(minStart, minEnd + 1);
}

猜你喜欢

转载自blog.csdn.net/tzyshiwolaogongya/article/details/80380547