Valid Palindrome Leetcode


#1

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Note: For the purpose of this problem, we define empty string as valid palindrome.

Example 1:

Input: "A man, a plan, a canal: Panama"
Output: true

Example 2:

Input: "race a car"
Output: false

#2

The validation is the easiest part, the complex part is cleaning the string or determining whether to use a character.

func isPalindrome(s string) bool {
    if len(s)==0{ return true}
    s = strings.ToLower(s)
    i, j := 0, len(s)-1
    for i<=j{
        if !isChar(s[i]){ 
            i++
        } else if !isChar(s[j]){
            j--
        } else{
            if s[i]!=s[j]{ return false}
            i++
            j--
        }
    }
    return true
}

func isChar(ch byte) bool{
    return (int(ch-'a')>=0 && int(ch-'a')<=26) || (int(ch-'0')>=0 && int(ch-'0')<=9)
}

#3

A different verison.

func isPalindrome(s string) bool {
    if len(s)==0{ return true}
    s = strings.ToLower(s)
    i, j := 0, len(s)-1
    for i<j{
        for i<j && !isChar(s[i]){ i++ }
        for i<j && !isChar(s[j]){ j-- }
        if s[i]!=s[j]{ return false}
        i++
        j--
    }
    return true
}

func isChar(ch byte) bool{
    return (int(ch-'a')>=0 && int(ch-'a')<=26) || (int(ch-'0')>=0 && int(ch-'0')<=9)
}