切换主题
覆盖子串篇
最小覆盖子串
hashMap + 滑动窗口
解题思路
JavaScript
const minWindow = (s, t) => {
const [map, m, n] = [new Map(), s.length, t.length]
if (m < n) return ''
let [need, minLen] = [n, m + 1]
let [i, j] = [-1, -1]
for (const char of t) {
map.set(char, (map.get(char) || 0) + 1)
}
let [l, r] = [0, 0]
while (r < m) {
let char = s.charAt(r++)
let cnt = map.get(char)
if (cnt != null) {
map.set(char, cnt - 1)
if (cnt > 0) need--
}
while (need === 0) {
if (r - l < minLen) {
minLen = r - l;
[i, j] = [l, r]
}
char = s.charAt(l++)
cnt = map.get(char)
if (cnt != null) {
map.set(char, cnt + 1)
if (cnt >= 0) need++
}
}
}
return s.substring(i, j)
}
时间复杂度:O(C*(m+n))
;空间复杂度:O(C)
。
字符串的排列
解题思路
JavaScript
const checkInclusion = (t, s) => {
const [map, m, n] = [new Map(), s.length, t.length]
if (m < n) return false
let need = n
for (const char of t) {
map.set(char, (map.get(char) || 0) + 1)
}
let [l, r] = [0, 0]
while (r < m) {
let char = s.charAt(r)
let cnt = map.get(char)
if (cnt != null) {
map.set(char, cnt - 1)
if (cnt > 0) need--
}
l = r++ - n
if (l >= 0) {
char = s.charAt(l)
cnt = map.get(char)
if (cnt != null) {
map.set(char, cnt + 1)
if (cnt >= 0) need++
}
}
if (need === 0) return true
}
return false
}
时间复杂度:O(C*(m+n))
;空间复杂度:O(C)
。
所有字母异位词
解题思路
JavaScript
const findAnagrams = (s, t) => {
const [map, m, n] = [new Map(), s.length, t.length]
if (m < n) return []
let [ret, need] = [[], n]
for (const char of t) {
map.set(char, (map.get(char) || 0) + 1)
}
let [l, r] = [0, 0]
while (r < m) {
let char = s.charAt(r)
let cnt = map.get(char)
if (cnt != null) {
map.set(char, cnt - 1)
if (cnt > 0) need--
}
l = r++ - n
if (l >= 0) {
char = s.charAt(l)
cnt = map.get(char)
if (cnt != null) {
map.set(char, cnt + 1)
if (cnt >= 0) need++
}
}
if (need === 0) ret.push(l + 1)
}
return ret
}
时间复杂度:O(C*(m+n))
;空间复杂度:O(C)
。