Skip to content

Instantly share code, notes, and snippets.

@BarakChamo
Created August 31, 2021 20:24
Show Gist options
  • Save BarakChamo/f4f264a67a171aaf68abb747a4927970 to your computer and use it in GitHub Desktop.
Save BarakChamo/f4f264a67a171aaf68abb747a4927970 to your computer and use it in GitHub Desktop.
Palindrome
function compare(s, i, p, n) {
const current = s[i]
const prev = i > 0 ? s[i - p] : ''
const next = i < (s.length - n) ? s[i + n] : ''
if(s.length == 1)
return false
if(prev == next)
return [p+1, n+1, true]
// return compare(s, i, p+1, n+1)
if(n == 1 && prev == current)
return [p+1, n, true]
// return compare(s, i, p+1, n)
return [p, n, false]
}
var longestPalindrome = function(s) {
let index = 0,
longest = 1,
p = 1,
n = 1
for (let i = 0; i < s.length; i++) {
let v = [1,1]
while (true) {
v = compare(s, i, v[0], v[1])
if ((v[0] + v[1]) > longest) {
index = i
longest = (v[0] + v[1])
p = v[0]
n = v[1]
}
if(!v[2]) break
}
}
const pali = s.substr(index - (p - 1), p + n - 1)
return pali
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment