文章目录
- 1 求最长公共前缀
- 1.1 暴力法
- 1.2 分治法
- 2 最长回文子串
- 2.1 暴力法
1 求最长公共前缀
1.1 暴力法
以第一个为基准,取其前缀,与其他字符串依次比较,如果全部相同,就更新res。res指向公共前缀的末尾。
var longestCommonPrefix = function(strs) {if (!strs || strs.length === 0) return ''if (strs.length === 1) return strs[0]const len = strs.lengthlet pre = '', index = 0, res = -1for (let i = 0; i < strs[0].length; i++) {let flag = truefor (let j = 1; j < len; j++) {pre = strs[0].slice(0, i+1)const tmp = strs[j].slice(0, i+1)if (pre !== tmp) {flag = false}}if (flag) res = i}return strs[0].slice(0, res+1)
};
1.2 分治法
var longestCommonPrefix = function(strs) {if (!strs || strs.length === 0) return ''return getCommonPrefix(strs, 0, strs.length-1)
};
// 分治
var getCommonPrefix = function(strs, left, right) {if (left >= right) return strs[left]const mid = Math.floor((left+right)/2)const leftCommonPrefix = getCommonPrefix(strs, left, mid)const rightCommonPrefix = getCommonPrefix(strs, mid+1, right)return compareTwo(leftCommonPrefix, rightCommonPrefix)
};
// 合并
var compareTwo = function(left, right) {const len = Math.min(left.length, right.length)for (let i = 0; i < len; i++) {if (left.charAt(i) !== right.charAt(i)) {return left.slice(0, i)}}return left.slice(0, len)
}
2 最长回文子串
2.1 暴力法
var longestPalindrome = function(s) {if (!s || s.length <= 1) return sconst len = s.lengthlet maxLen = 0, max = ''for (let i = 0; i < len; i++) {for (let j = i+1; j < len; j++) {let sub = s.slice(i, j+1)if (isHuiWen(sub) && sub.length > maxLen) {max = submaxLen = sub.length}}}// 如果找不到 就返回最长第一个return max === ''? s.charAt(0):max
};var isHuiWen = function(s) {let i = 0, j = s.length-1while (i < j) {if (s.charAt(i) !== s.charAt(j)) {return false}i++j--}return true
}