add: 最长回文字符串
This commit is contained in:
parent
2120bcdecf
commit
a2ccc4764b
1
.vscode/settings.json
vendored
1
.vscode/settings.json
vendored
@ -21,6 +21,7 @@
|
||||
"nums",
|
||||
"powx",
|
||||
"pwwkew",
|
||||
"qian",
|
||||
"subarray",
|
||||
"subarrays",
|
||||
"umghlrlose",
|
||||
|
@ -95,6 +95,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
|
||||
|
||||
- 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)
|
||||
|
||||
- LeetCode 1371. 每个元音包含偶数次的最长子字符串 <https://leetcode-cn.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/>
|
||||
|
36
src/string/longest-palindromic-substring.js
Normal file
36
src/string/longest-palindromic-substring.js
Normal 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)
|
||||
// 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
|
6
test/string/longest-palindromic-substring.test.js
Normal file
6
test/string/longest-palindromic-substring.test.js
Normal 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')
|
||||
})
|
Loading…
Reference in New Issue
Block a user