难度标识:
⭐:简单,⭐⭐:中等,⭐⭐⭐:困难。
tips:这里的难度不是根据LeetCode难度定义的,而是根据我解题之后体验到题目的复杂度定义的。
1. 无重复字符的最长子串 ⭐
思路
通过动态地移动滑动窗口来维护一个始终不包含重复字符的子字符串,同时记录并更新这个子字符串的最大长度。
代码
var lengthOfLongestSubstring = function (s) {
let left = 0, right = 0, count = 0;
const window = {}
while (right < s.length) {
const ch = s[right++]
window[ch] = (window[ch] || 0) + 1
while (window[ch] > 1) {
const d = s[left++]
window[d]--
}
count = Math.max(count, right - left)
}
return count
}
2.找到字符串中所有字母异位词 ⭐
思路
-
1.首先使用一个对象记录p中的每个字符出现的次数
-
2.使用滑动窗口,当滑动窗口中的字符数量与p的长度相等时,我们判断每个字符出现的次数是否相等,如果也相等,那此时滑动窗口内的字符就是p的异位词子串,我们将其实索引
push到结果数组中,并且我们开始收缩滑动窗口。进行下一轮的循环查找。
代码
var findAnagrams = function (s, p) {
const obj = {}
for (let ch of p) {
obj[ch] = (obj[ch] || 0) + 1
}
let left = 0, right = 0, count = 0;
const window = {}
const needLen = Object.keys(obj).length
const res = []
while (right < s.length) {
const c = s[right++]
if (obj[c]) {
window[c] = (window[c] || 0) + 1
if (obj[c] === window[c]) {
count++
}
}
while (right - left === p.length) {
if (count === needLen) {
res.push(left)
}
const d = s[left++]
if (obj[d]) {
if (obj[d] === window[d]) {
count--
}
window[d]--
}
}
}
return res
};
滑动窗口类的题目基本上写出来的代码都差不多,首先拿一个对象去记录目标相关的内容,然后创建滑动窗口,然后找好收缩条件即可。