Find largest Substring which is palindrome

Find largest Substring which is palindrome

There are case which might require you to find out substring which is largest palindrome.

Here in this example, we’ll achieve it by finding all the palindrome substring and then find out the largest one from it.

function longestPalindrome(str){
  var arr = str.split("");
  var allPalindrome = [];
  
  for(var i = 0; i < arr.length; i++){
    var temp = "";
    temp = arr[i];
    for(var j = i + 1; j < arr.length; j++){
      temp += arr[j];
      if(temp.length > 2 && temp === temp.split("").reverse().join("")){
        allPalindrome.push(temp);
      }
    }
  }
  
  var count = 0;
  var longestPalindrome = "";
  for(var i = 0; i < allPalindrome.length; i++){
    if(count >= allPalindrome[i].length){
      longestPalindrome = allPalindrome[i-1]; 
    }
    else{
      count = allPalindrome[i].length;
    }
  }
  return longestPalindrome;
}

Output

var longestPal= longestPalindrome("abc123321");

console.log(console.log(longestPal))

123321

 

Leave a Reply

Your email address will not be published. Required fields are marked *