代码拉取完成,页面将自动刷新
package com.hit.basmath.interview.top_interview_questions.hard_collection.array_and_strings;
import java.util.HashMap;
/**
* 76. Minimum Window Substring
* <p>
* Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
* <p>
* Example:
* <p>
* Input: S = "ADOBECODEBANC", T = "ABC"
* Output: "BANC"
* <p>
* Note:
* <p>
* 1. If there is no such window in S that covers all characters in T, return the empty string "".
* 2. If there is such window, you are guaranteed that there will always be only one unique minimum window in S.
*/
public class _76 {
public String minWindow(String s, String t) {
if (s == null || s.length() < t.length() || s.length() == 0) {
return "";
}
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for (char c : t.toCharArray()) {
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
}
int left = 0;
int minLeft = 0;
int minLen = s.length() + 1;
int count = 0;
for (int right = 0; right < s.length(); right++) {
if (map.containsKey(s.charAt(right))) {
map.put(s.charAt(right), map.get(s.charAt(right)) - 1);
if (map.get(s.charAt(right)) >= 0) {
count++;
}
while (count == t.length()) {
if (right - left + 1 < minLen) {
minLeft = left;
minLen = right - left + 1;
}
if (map.containsKey(s.charAt(left))) {
map.put(s.charAt(left), map.get(s.charAt(left)) + 1);
if (map.get(s.charAt(left)) > 0) {
count--;
}
}
left++;
}
}
}
if (minLen > s.length()) {
return "";
}
return s.substring(minLeft, minLeft + minLen);
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。