Last active
August 29, 2015 14:01
-
-
Save kwyn/3db7ff67fb1c4d58b8d6 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 longestPalindrome = function (string) { | |
// Your code here | |
// Sliding window problem. | |
// If string is palindrom, return string | |
// else check if substring of length stringLength-n is palindrome. | |
// As soon as you get a palindrome you've found the longest palindrome | |
// since you're shrinking the window and you want the longest one. | |
var stringLength = string.length | |
var n = 0; | |
while( n < stringLength){ | |
for( var i = 0; i < =n; i++ ){ | |
if( isPalandrome( string.substring(i, stringLength-n+i) ) ){ | |
return string.substring(i, stringLength-n+i); | |
} | |
} | |
n++; | |
} | |
return false; | |
} | |
var isPalandrome = function(string){ | |
// Code here. | |
// Check if the first letter is the same as the last. | |
//decriment and work your way in. 2nd same as 2nd to last etc | |
//if ever this is not true. We return false | |
//We only have to do this for half the string. :D | |
var l = string.length | |
for(var i = 0; i < l/2; i++){ | |
if( string.charAt(i) !== string.charAt(l-i-1) ) return false; | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment