Code Wars: longest_palindrome (6 kyu)

Link to code challenge

Find the length of the longest substring in the given string s that is the same in reverse. As an example, if the input was “I like racecars that go fast”, the substring (racecar) length would be 7. If the length of the input string is 0, the return value must be 0.

//Loop thru string and find longest substring that is also a palindrome //Efficiency- start with longest length first (each "outer" loop still looping to shorter //strings but done prior to "inner" loops which have longer strings- can be more efficient?) longestPalindrome=function(s){ if (s === "") return 0; else if (s.length === 1) return 1; let mainPointer = s.length; let subPointer = 0; let largest = 0; while (subPointer < s.length) { if (mainPointer >= 0) { //refactored- instead of pushing to new array let newString = s.slice(subPointer, mainPointer); //can this be refactored by comparing the two endpoints of the string but longer code? if ( newString === newString.split("").reverse().join("") ) { //used Math.max instead of another conditional in if statement largest = Math.max(largest, newString.length); //break out of this "loop" as substrings below this one would be shorter in length mainPointer = s.length; subPointer++; } else mainPointer--; } else { mainPointer = s.length; subPointer++; } } return largest; }

Comments

Popular posts from this blog

Code Wars: Data Reverse (6 kyu)

Code Wars: Find the odd int