Valid Palindrome

Solution in Go

func isPalindrome(s string) bool {
    if len(s) <= 1 {
        return true
    }

    start := 0
    end := len(s) - 1

    for start <= end {
        if !isLetterOrNumber(s[start]) {
            start++
            continue
        }

        if !isLetterOrNumber(s[end]) {
            end--
            continue
        }

        if toLower(s[start]) != toLower(s[end]) {
            return false
        }

        start++
        end--
    }

    return true
}

func isLetterOrNumber(c uint8) bool {
    return (c >= '0' && c <= '9') ||
        (c >= 'a' && c <= 'z') ||
        (c >= 'A' && c <= 'Z')
}

func toLower(c uint8) uint8 {
    if c >= 'A' && c <= 'Z' {
        return c + 32
    }

    return c
}
Subscribe via email

Get notified once/twice per month when new articles are published.

Copyright © 2022 - 2024 TheDeveloperCafe.
The Go gopher was designed by Renee French.