Created
November 8, 2024 06:33
-
-
Save sAVItar02/cc1ea4c6fcfdb4e534bf93fba40d4f5a to your computer and use it in GitHub Desktop.
Longest Palindromic Substring
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
/** | |
* @param {string} s | |
* @return {string} | |
*/ | |
var longestPalindrome = function(s) { | |
let res = ""; | |
let max = 0; | |
for(let i=0; i<s.length; i++) { | |
let l = i; | |
let r = i; | |
while(l >= 0 && r <= s.length - 1 && s[l] == s[r]) { | |
if(r - l + 1 > max) { | |
max = r - l + 1; | |
res = s.substr(l, max); | |
} | |
l--; | |
r++; | |
} | |
let start = i; | |
let end = i+1; | |
while(start >= 0 && end <= s.length - 1 && s[start] == s[end]) { | |
if(end - start + 1 > max) { | |
max = end - start + 1; | |
res = s.substr(start, max); | |
} | |
start--; | |
end++; | |
} | |
} | |
return res; | |
}; | |
// Run and loop and consider the current element to be the center element | |
// For odd length | |
// expand outward on both sides from the center element until one of these conditions fail: | |
// i. left pointer is not out of bounds | |
// ii. right pointer is not out of bounds | |
// iii. value and left pointer is the same as the value at right pointer | |
// keep checking if the current length is greater the the max value, if yes then update max value | |
// For even Length | |
// Do the same except the pointers start from the center and center + 1; | |
// Time: O(n^2) | |
// Space: O(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment