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

1 Answer

0 votes
using System;

class Program
{
    // Check if a substring of str from left to right (inclusive) is a palindrome
    static bool IsPalindrome(string str, int left, int right) {
        while (left < right) {
            if (str[left++] != str[right--]) {
                return false;
            }
        }
        return true;
    }

    // Check and print whether substrings defined by ranges are palindromes
    static void CheckRangesForPalindrome(string str, int[,] ranges) {
        int rows = ranges.GetLength(0);  
        
        for (int i = 0; i < rows; i++) {
            int start = ranges[i, 0];
            int end = ranges[i, 1];
            string substring = str.Substring(start, end - start + 1);

            Console.Write(substring + ": ");
            Console.WriteLine(IsPalindrome(str, start, end) ? "Palindrome" : "Not palindrome");
        }
    }

    static void Main()
    {
        string str = "abcddcbeebc";
        int[,] ranges = {
            {2, 5},
            {5, 10},
            {3, 7}
        };

        CheckRangesForPalindrome(str, ranges);
    }
}


/*
run:

cddc: Palindrome
cbeebc: Palindrome
ddcbe: Not palindrome

*/

 



answered 5 hours ago by avibootz

Related questions

...