链表
回文链表
反转链表
javascript
reversList = (head) => {
let pre = null;
let cur = head;
while(cur) {
const next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
合并K个升序链表
【LeetCode 直通车】:25 K 个一组翻转链表(困难)
字符串
动态规划解决
js
dp []
i === j dp[i][j] === true
j - i === 1 dp[i][j] === true
上面和一起就是
j - i < 2 dp[i][j] = s[i] === s[j]
j - i > 2 s[i] === s[j] && dp[i][j] = dp[i+1][j-1]
转移 i+1 j -1
所以需要从 i-- j++ 进行循环
/**
* @param {string} s
* @return {string}
*/
var longestPalindrome = function(s) {
let res = ''
let len = s.length;
let dp = new Array(len).fill().map(item => new Array(len).fill(false));
for(let i = len - 1; i >= 0; i--) {
for(let j = i; j < len; j++) {
dp[i][j] = s[i] === s[j] && (j-i <2 || dp[i+1][j-1])
if(dp[i][j] && res.length < j -i +1) {
res = s.slice(i, j+1)
}
}
}
return res;
};
【LeetCode 直通车】:3 无重复字符的最长子串(中等)
使用 hash 来标识该数字是否出现过
从左往右 进行滑动窗口
当有重复 窗口向右加 1 并删除最左字符
javascript
/**
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstring = function (s) {
let len = s.length;
if (len <= 1) return len;
const set = new Set();
let right = 0;
let max = 0;
for (let i = 0; i < len; i++) {
if (i > 0) {
set.delete(s[i - 1])
}
while (right < len && !set.has(s[right])) {
set.add(s[right]);
right++
}
max = Math.max(max, right - i)
}
return max
};