字符串
👉 【LeetCode 直通车】:14 最长公共前缀(简单)
javascript
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function(strs) {
strs = strs.sort((a, b) => a.length - b.length);
let cur = strs[0];
let prefix;
for(let i = 0; i < cur.length; i++) {
prefix = cur.slice(0, i+1);
let res = strs.every(item => item.startsWith(prefix));
if(!res) {
return cur.slice(0, i);
}
}
return prefix
};
👉 【LeetCode 直通车】:3 无重复字符的最长子串(中等)
javascript
/**
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstring = function(s) {
let max = 0;
let l = 0, r = 0;
let dep = new Set();
while(r < s.length) {
if(!dep.has(s[r])) {
dep.add(s[r]);
max = Math.max(dep.size, max);
r++;
} else {
while(s[l] !== s[r]) {
dep.delete(s[l]);
l++;
}
dep.delete(s[l]);
l++;
}
}
return max
};
👉 【LeetCode 直通车】:5 最长回文子串(中等)
# [最长回文子串](https://leetcode.com/problems/longest-palindromic-substring/submissions/1203559458/)
```javascript
dp[i][j] 表示 字符串 i 到 j 是否回文
dp[i][j] = dp[i+1][j-1] && s[i] === s[j];
边界条件:
长度 1
可以知道 i === j dp[i][j] = true
长度 2
s[i] === s[j] dp[i][j] = true
javascript
/**
* @param {string} s
* @return {string}
*/
var longestPalindrome = function(s) {
let len = s.length;
if(len < 2) return s;
let res = ''
let dp = new Array(len).fill().map(item => new Array(len).fill(false));
for(let i = 0; i < len; i++) {
dp[i][i] = true;
}
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;
};
中心扩散
javascript
/**
* @param {string} s
* @return {string}
*/
var longestPalindrome = function(s) {
let max = '';
let len = s.length;
const helper = (l, r) => {
while(l >= 0 && r < len && s[l] == s[r]) {
l--;
r++;
}
if(r-l-1 > max.length) {
max = s.slice(l + 1, r);
}
}
for(let i = 0; i < len; i++) {
helper(i, i);
helper(i, i+1);
}
return max;
};
👉 【LeetCode 直通车】:76 最小覆盖子串(困难)
javascript
/**
* @param {string} s
* @param {string} t
* @return {string}
*/
var minWindow = function (s, t) {
const len = s.length;
let l = -1, r = len;
const hashS = {};
const hashT = {};
let less = 0;
let left = 0;
for (let i in t) {
const key = t[i];
if (!hashT[key]) {
hashT[key] = 0;
less++;
}
hashT[key]++
}
for (let right = 0; right < len; right++) {
let key = s[right];
if (!hashS[key]) {
hashS[key] = 0;
}
hashS[key]++;
if(hashS[key] === hashT[key]) {
less--
}
while(less === 0) {
if(right - left < r -l) {
r = right;
l = left;
}
const deleteKey = s[left];
left++;
if(hashS[deleteKey] === hashT[deleteKey]) {
less++
}
hashS[deleteKey]--
}
}
return l < 0 ? "" : s.slice(l, r + 1);
};