Last active
March 26, 2020 05:36
-
-
Save ms314006/9fa14676bed920b575be0a3189d3e326 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const isPalindromic = (s) => { | |
const center = Math.floor(s.length / 2); | |
for(let i = 0; i <= center; i += 1) { | |
if(s[i] !== s[s.length - 1 - i]) { | |
return false; | |
} | |
} | |
return true; | |
} | |
const findLastSameStringIndex = (string, target, lastIndex) => { | |
for(let i = lastIndex - 1; i >= 0; i -= 1) { | |
if (target === string[i]) { | |
return i; | |
} | |
} | |
} | |
var longestPalindrome = function(s) { | |
if (s === '') return ''; | |
let answer = s[0]; | |
for (let i = 0; i < s.length; i+= 1) { | |
let lastSameStrIndex = findLastSameStringIndex(s, s[i], s.length); | |
while(lastSameStrIndex !== i) { | |
const currentStr = s.slice(i, lastSameStrIndex + 1); | |
if (currentStr.length <= answer.length) break; | |
if (isPalindromic(currentStr)) { | |
answer = currentStr; | |
break; | |
} | |
lastSameStrIndex = findLastSameStringIndex(s, s[i], lastSameStrIndex); | |
} | |
} | |
return answer; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment