文章 224
评论 6
浏览 177804
Palindrome - 125. Valid Palindrome

Palindrome - 125. Valid Palindrome

  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
}


标题:Palindrome - 125. Valid Palindrome
作者:michael
地址:https://www.bitbo-liuyang.com/articles/2019/07/15/1563200953256.html

Nothing just happens, it's all part of a plan.

取消