문제
Given two strings s
and t
of lengths m and n respectively, return the minimum window substring of s
such that every character in t
(including duplicates) is included in the window. If there is no such substring, return the empty string ""
.
The testcases will be generated such that the answer is unique.
예시
Example 1:
Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"
Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.
Example 2:
Input: s = "a", t = "a"
Output: "a"
Explanation: The entire string s is the minimum window.
Example 3:
Input: s = "a", t = "aa"
Output: ""
Explanation: Both 'a's from t must be included in the window.
Since the largest window of s only has one 'a', return empty string.
조건
- m == s.length
- n == t.length
- 1 <= m, n <= 105
- s and t consist of uppercase and lowercase English letters.
답
s에서 window를 만들어 왼쪽에서 오른쪽으로 이동하며 각 구간을 검사합니다.
t와 s의 window에 들어가는 문자의 개수는 접근 속도를 위해 hash map을 사용합니다.
Window의 오른쪽 끝은 window가 t를 모두 포함할 때 까지 한 칸씩 이동하며 window를 확장합니다.
Window의 왼쪽 끝은 window가 t를 모두 포함하는 상태가 아닐 때 까지 한 칸씩 이동하며 window를 축소합니다.
Window의 오른쪽 끝이 이동할 때마다 window의 구간 크기를 최소 크기와 비교해가며 최고 window 크기를 구합니다.
/**
* @param {string} s
* @param {string} t
* @return {string}
*/
var minWindow = function(s, t) {
const sLen = s.length;
const tLen = t.length;
const sMap = new Map();
const tMap = new Map();
let left = 0, right = 0, window = 0;
let minWinLen = sLen, minWin = "";
if (sLen < tLen) return minWin
for (let i=0; i<tLen; ++i) {
tMap.set(t[i], (tMap.get(t[i]) + 1) || 1);
}
for (const char of s) {
sMap.set(char, (sMap.get(char) + 1) || 1);
if (tMap.has(char) && tMap.get(char) === sMap.get(char)) {
window++;
}
while (window == tMap.size) {
if (minWinLen >= right - left + 1) {
minWinLen = right - left + 1;
minWin = s.slice(left, right + 1);
}
sMap.set(s[left], sMap.get(s[left]) - 1);
if (tMap.has(s[left]) && tMap.get(s[left]) > sMap.get(s[left])) {
window--;
}
left++;
}
right++;
}
return minWin
};
s 크기 M, t 크기 N에 대해
시간 복잡도 : O(M+N)
공 복잡도 : O(M+N)
'CS > PS' 카테고리의 다른 글
[PS] Leet | 5. 가장 긴 팰린드롬 하위문자열 (0) | 2025.06.27 |
---|---|
[PS] Leet | 125. 팰린드롬 찾기 (0) | 2025.06.20 |
[PS] Leet | 424. 가장 긴 반복되는 철자로 대체하기 (0) | 2025.06.18 |
[PS] Leet | 48. 이미지 회전 (0) | 2025.05.21 |
[PS] Leet | 143. 리스트 재배치 (0) | 2025.05.12 |