【发布时间】:2020-04-02 01:56:21
【问题描述】:
我发现这个解决方案对于在子字符串中查找最长回文的算法问题很有意义。但是,我很难理解扩展功能实际上在做什么。我以为它会从中心运行,但控制台日志显示它是为整个字符串运行的。我很难理解为什么它会进入与 s[begin] === s[end] 不同的任何字符的 while 循环,这就是我认为这条线正在阻止的。我不确定为什么 expand 也被调用了两次。另外,为什么我们在返回子字符串时要添加begin + 1 而不仅仅是begin。代码如下。任何有关扩展如何工作的说明都将不胜感激。
var longestPalindrome = function (s) {
//either when empty string or is a single character
if (!s || s.length <= 1) return s
let longest = s.substring(0, 1)
for (let i = 0; i < s.length; i++) {
let temp = expand(s, i, i, 'first')
// console.log(temp, 'i am the first')
if (temp.length > longest.length) {
longest = temp
}
temp = expand(s, i, i + 1, 'second')
// console.log(temp, 'i am the second')
if (temp.length > longest.length) {
longest = temp
}
}
return longest
}
const expand = (s, begin, end, counter) => {
while (begin >= 0 && end <= s.length - 1 && s[begin] === s[end]) {
console.log(s, 'i am string')
console.log(begin, 'i am begin')
console.log(end, 'i am begin')
console.log(s[begin], s[end])
console.log(counter)
begin--
end++
}
return s.substring(begin + 1, end)
}
console.log(longestPalindrome('cbbd'))
console.log(longestPalindrome('babad'))
console.log(longestPalindrome('ac'))
console.log(longestPalindrome('abb'))
【问题讨论】:
标签: javascript algorithm palindrome