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

1 Answer

0 votes
public class PalindromeChecker {

    // Check if a substring of str from left to right (inclusive) is a palindrome
    public static boolean isPalindrome(String str, int left, int right) {
        while (left < right) {
            if (str.charAt(left++) != str.charAt(right--)) {
                return false;
            }
        }
        return true;
    }

    // Check and print whether substrings defined by ranges are palindromes
    public static void checkRangesForPalindrome(String str, int[][] ranges) {
        for (int[] range : ranges) {
            int start = range[0];
            int end = range[1];
            String substring = str.substring(start, end + 1);

            System.out.print(substring + ": ");
            System.out.println(isPalindrome(str, start, end) ? "Palindrome" : "Not palindrome");
        }
    }

    public static void main(String[] args) {
        String str = "abcddcbeebc";
        int[][] ranges = {
            {2, 5},
            {5, 10},
            {3, 7}
        };

        checkRangesForPalindrome(str, ranges);
    }
}


/*
run:

cddc: Palindrome
cbeebc: Palindrome
ddcbe: Not palindrome

*/

 



answered 12 hours ago by avibootz

Related questions

...