How to check whether each substring range (L to R) from an array of substring ranges is a palindrome in JavaScript

1 Answer

0 votes
const str = "abcddcbeebc";
const ranges = [
  [2, 5],
  [5, 10],
  [3, 7]
];

// Check if a substring of str between left and right indices is a palindrome
function isPalindrome(str, left, right) {
  while (left < right) {
    if (str[left++] !== str[right--]) {
      return false;
    }
  }
  
  return true;
}

// Check and print whether substrings defined by ranges are palindromes
function checkRangesForPalindrome(str, ranges) {
  for (const [start, end] of ranges) {
    const substring = str.slice(start, end + 1);
    const result = isPalindrome(str, start, end) ? "Palindrome" : "Not palindrome";
    console.log(`${substring}: ${result}`);
  }
}

checkRangesForPalindrome(str, ranges);


/*
run:

cddc: Palindrome
cbeebc: Palindrome
ddcbe: Not palindrome

*/

 



answered 3 hours ago by avibootz

Related questions

...