We often think that recursive is the best solution, but in some cases it is the worst. An example is given below:
It works for larger palindromes but takes a lot of time if palindrome is not most of the input string.
RUN THE CODE HERE: https://repl.it/@VinitKhandelwal/longest-palindrome-recursive-javascript
Problem:
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
const longestPalindrome = str => {
if (str.length > 1){
let [palindrome1, palindrome2] = [str, str];
for (let i=0;i<Math.floor(str.length/2);i++) {
if(str[i]!==str[str.length-i-1]) {
palindrome1 = longestPalindrome(str.slice(0, str.length-1));
palindrome2 = longestPalindrome(str.slice(1, str.length));
break;
}
}
return palindrome2.length > palindrome1.length ? palindrome2 : palindrome1;
} else {
return str;
}
}
console.log(longestPalindrome("babababababababababababa"));
Output
babababababababababababIt works for larger palindromes but takes a lot of time if palindrome is not most of the input string.
RUN THE CODE HERE: https://repl.it/@VinitKhandelwal/longest-palindrome-recursive-javascript
Comments
Post a Comment