Palindrome - 125. Valid Palindrome

6
  1. Valid Palindrome

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

思路:

题目意思是说给定一个字符串,只看字母和数字是否是回文字符串,使用two pointer来做,从前扫,从后扫,寻找首尾位置的字母或者数字,进行比对。

代码:

golang:

func isPalindrome(s string) bool {    
    left := 0
    right := len(s) - 1
    
    for left < right {
        if !isChar(s[left]) {
            left++
        } else if !isChar(s[right]) {
            right--
        } else {
            if toLower(s[left]) == toLower(s[right]) {
                left++
                right--
            } else {
                return false 
            }
        }
    }
    
    return true
}

func isChar(c byte) bool {
    return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9')
}

func toLower(c byte) byte {
    if 'A' <= c && c <= 'Z' {
        return c + ('a' - 'A')
    }
    return c
}