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

1 Answer

0 votes
const str: string = "abcddcbeebc";

const ranges: [number, number][] = [
  [2, 5],
  [5, 10],
  [3, 7]
];

// Check if a substring of str between left and right indices is a palindrome
function isPalindrome(str: string, left: number, right: number): boolean {
  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: string, ranges: [number, number][]): void {
  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

...