2021-10-12:验证回文串。给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。说明:本题中,我们将空字符串定义为有效的回文串 。输入: “A man, a plan

2021-10-12:验证回文串。给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。说明:本题中,我们将空字符串定义为有效的回文串 。输入: “A man, a plan, a canal: Panama”。输出: true。解释:“amanaplanacanalpanama” 是回文串。力扣125。

福大大 答案2021-10-12:

自然智慧即可。首尾指针比较,向中间移动。
时间复杂度:O(N)。
空间复杂度:O(1)。

代码用golang编写。代码如下:

package main

import "fmt"

func main() {
    ret := isPalindrome("abc ba")
    fmt.Println(ret)
}

// 忽略空格、忽略大小写 -> 是不是回文
// 数字不在忽略大小写的范围内
func isPalindrome(s string) bool {
    if len(s) == 0 {
        return true
    }
    str := []byte(s)
    L := 0
    R := len(str) - 1
    for L < R {
        // 英文(大小写) + 数字
        if validChar(str[L]) && validChar(str[R]) {
            if !equal(str[L], str[R]) {
                return false
            }
            L++
            R--
        } else {

            L += twoSelectOne(validChar(str[L]), 0, 1)
            R -= twoSelectOne(validChar(str[R]), 0, 1)
        }
    }
    return true
}

func validChar(c byte) bool {
    return isLetter(c) || isNumber(c)
}

func equal(c1 byte, c2 byte) bool {
    if isNumber(c1) || isNumber(c2) {
        return c1 == c2
    }
    // a  A   32
    // b  B   32
    // c  C   32
    return (c1 == c2) || (getMax(c1, c2)-getMin(c1, c2) == 32)
}

func isLetter(c byte) bool {
    return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
}

func isNumber(c byte) bool {
    return (c >= '0' && c <= '9')
}

func getMax(a byte, b byte) byte {
    if a > b {
        return a
    } else {
        return b
    }
}
func getMin(a byte, b byte) byte {
    if a > b {
        return a
    } else {
        return b
    }
}

func twoSelectOne(c bool, a int, b int) int {
    if c {
        return a
    } else {
        return b
    }
}

执行结果如下:
图片


左神java代码

posted @ 2021-10-12 22:26  福大大架构师每日一题  阅读(17)  评论(0编辑  收藏  举报  来源