Golang solution (6ms)


  • 0
    func isPalindrome(s string) bool {
        i, j := 0, len(s) - 1
        for i < j {
            if !isAlphaNumeric(s[i]) {
                i++
                continue
            }
            if !isAlphaNumeric(s[j]) {
                j--
                continue
            }
            if toLower(s[i]) != toLower(s[j]) { return false }
            i++
            j--
        }
        return true
    }
    
    func isAlphaNumeric(b byte) bool {
        if b >= 'A' && b <= 'Z' || b >= 'a' && b <= 'z' || b >= '0' && b <= '9' { return true }
        return false
    }
    
    func toLower(b byte) byte {
        if b >= 'A' && b <= 'Z' { return 'a' + b - 'A' }
        return b
    }
    

    Here is a simpler version using the unicode.ToLower, unicode.IsNumber and unicode.IsLetter APIs but is slightly slower (16ms)

    func isPalindrome(s string) bool {
        i, j := 0, len(s) - 1
        for i < j {
            if !isAlphaNumeric(s[i]) { i++; continue }
            if !isAlphaNumeric(s[j]) { j--; continue }
            if unicode.ToLower(rune(s[i])) != unicode.ToLower(rune(s[j])) { return false }
            i, j = i + 1, j - 1
        }
        return true
    }
    
    func isAlphaNumeric(b byte) bool {
        return unicode.IsLetter(rune(b)) || unicode.IsNumber(rune(b))
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.