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

1 Answer

0 votes
package main

import (
    "fmt"
)

// isPalindrome checks if the substring of s from left to right (inclusive) is a palindrome.
func isPalindrome(s string, left, right int) bool {
    for left < right {
        if s[left] != s[right] {
            return false
        }
        left++
        right--
    }
    
    return true
}

// checkRangesForPalindrome prints whether each substring defined by ranges is a palindrome.
func checkRangesForPalindrome(s string, ranges [][2]int) {
    for _, r := range ranges {
        start, end := r[0], r[1]
        substring := s[start : end+1]
        fmt.Printf("%s: ", substring)
        if isPalindrome(s, start, end) {
            fmt.Println("Palindrome")
        } else {
            fmt.Println("Not palindrome")
        }
    }
}

func main() {
    s := "abcddcbeebc"
    ranges := [][2]int{
        {2, 5},
        {5, 10},
        {3, 7},
    }

    checkRangesForPalindrome(s, ranges)
}



/*
run:

cddc: Palindrome
cbeebc: Palindrome
ddcbe: Not palindrome

*/

 



answered 1 hour ago by avibootz

Related questions

...