Created
March 2, 2017 15:15
-
-
Save vvasabi/f7cbd633d759d21dadd82426836e605a 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
var Substring = function(s, e) { | |
this.s = s; | |
this.e = e; | |
this.l = e - s; | |
}; | |
var longestPalindromeFromOffset = function(s, i) { | |
var j, | |
long = new Substring(0, 1); | |
for (j = 1; (j <= (s.length - i)) && ((i - j) >= 0); j++) { | |
if (s.charAt(i - j) != s.charAt(i + j)) { | |
break; | |
} | |
if ((j * 2 + 1) > long.l) { | |
long = new Substring(i - j, i + j + 1); | |
} | |
continue; | |
} | |
for (j = 0; (j <= (s.length - i)) && ((i - j) >= 0); j++) { | |
if ((j > (s.length - i)) || (s.charAt(i - j) != s.charAt(i + j + 1))) { | |
break; | |
} | |
if ((j * 2 + 2) > long.l) { | |
long = new Substring(i - j, i + j + 2); | |
} | |
} | |
return long; | |
}; | |
var longestPalindrome = function(s) { | |
var i, | |
j, | |
long = new Substring(0, 1), | |
mid = Math.ceil(s.length / 2), | |
result; | |
for (i = 0; i <= mid; i++) { | |
if ((((s.length - mid - i) * 2 + 1) < long.l) && (((mid - i) * 2) < long.l)) { | |
break; | |
} | |
if (((mid + i) < s.length) && (((s.length - mid - i) * 2 + 1) > long.l)) { | |
result = longestPalindromeFromOffset(s, mid + i); | |
if (result.l > long.l) { | |
long = result; | |
} | |
} | |
if (((mid - i - 1) >= 0) && (((mid - i) * 2) > long.l)) { | |
result = longestPalindromeFromOffset(s, mid - i - 1); | |
if (result.l > long.l) { | |
long = result; | |
} | |
} | |
} | |
return s.substring(long.s, long.e); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment