add: 最长回文字符串

This commit is contained in:
yi-ge 2020-05-22 21:25:03 +08:00
parent 2120bcdecf
commit a2ccc4764b
4 changed files with 48 additions and 0 deletions

View File

@ -21,6 +21,7 @@
"nums", "nums",
"powx", "powx",
"pwwkew", "pwwkew",
"qian",
"subarray", "subarray",
"subarrays", "subarrays",
"umghlrlose", "umghlrlose",

View File

@ -95,6 +95,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
- LeetCode 1108. IP 地址无效化 <https://leetcode-cn.com/problems/defanging-an-ip-address/> - LeetCode 1108. IP 地址无效化 <https://leetcode-cn.com/problems/defanging-an-ip-address/>
- [最长回文子串](src/string/longest-palindromic-substring.js)
- LeetCode 5. 最长回文子串 <https://leetcode-cn.com/problems/longest-palindromic-substring/>
- LintCode 200. 最长回文子串 <https://www.lintcode.com/problem/longest-palindromic-substring/>
- [每个元音包含偶数次的最长子字符串](src/string/find-the-longest-substring-containing-vowels-in-even-counts.js) - [每个元音包含偶数次的最长子字符串](src/string/find-the-longest-substring-containing-vowels-in-even-counts.js)
- LeetCode 1371. 每个元音包含偶数次的最长子字符串 <https://leetcode-cn.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/> - LeetCode 1371. 每个元音包含偶数次的最长子字符串 <https://leetcode-cn.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/>

View File

@ -0,0 +1,36 @@
export const longestPalindrome = function (s) {
if (!s || !s.trim()) return ''
if (s.length === 1) return s
if (s.length === 2) return s[0] === s[1] ? s[0] + s[1] : s[1]
let result = ''
/**
*扩散坐标
*/
const calPalindromeIndex = function (left, right, s) {
const len = s.length
while (left >= 0 && right < len && s[left] === s[right]) {
left--
right++
}
return { left: left + 1, right: right }
}
for (let i = 0, len = s.length; i < len; i++) {
let even = ''
let odd = ''
if (s[i] === s[i + 1]) {
// 经过当前位与下一位判断已构成回文,扩散位直接从下一位开始,可以提速
const evenIndex = calPalindromeIndex(i - 1, i + 2, s)
even = s.slice(evenIndex.left, evenIndex.right)
}
const oddIndex = calPalindromeIndex(i - 1, i + 1, s)
odd = s.slice(oddIndex.left, oddIndex.right)
const re = odd.length > even.length ? odd : even
result = result.length > re.length ? result : re
}
return result
}
// 作者liu-zi-qian-2
// 链接https://leetcode-cn.com/problems/longest-palindromic-substring/solution/5-zui-chang-hui-wen-zi-chuan-by-liu-zi-qian-2/
// 来源力扣LeetCode
// 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

View File

@ -0,0 +1,6 @@
import { longestPalindrome } from '../../src/string/longest-palindromic-substring'
test('最长回文字符串', () => {
expect(longestPalindrome('babad')).toBe('aba') // bab也是有效答案
expect(longestPalindrome('cbbd')).toBe('bb')
})