验证回文串

125. 验证回文串

难度 ⭐

给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。

说明:本题中,我们将空字符串定义为有效的回文串。

示例 1:

输入: "A man, a plan, a canal: Panama"
输出: true

示例 2:

输入: "race a car"
输出: false

思路

遍历移除特殊字符,在判断是否为回文

coding

class Solution:
    def isPalindrome(self, s: str) -> bool:
        #转换小写 移除符号和标点
        temp = ""
        s = s.lower()
        for c in s:
            if c.isalnum():
                temp += c

        left,right = 0,len(temp)-1
        while left<right:
            if temp[left] != temp[right]:
                return False
            left += 1
            right -= 1
        return True

使用正则表达式

#正则
class Solution:
    def isPalindrome(self, s: str) -> bool:
        #re.sub(pattern, repl, string)
        temp = re.sub(r"[^A-Za-z0-9]","", s).lower()
        return temp == temp[::-1]

680. 验证回文字符串 Ⅱ

难度 ⭐

给定一个非空字符串 s最多删除一个字符。判断是否能成为回文字符串。

示例 1:

输入: "aba"
输出: True

示例 2:

输入: "abca"
输出: True
解释: 你可以删除c字符。

注意:

  1. 字符串只包含从 a-z 的小写字母。字符串的最大长度是50000。

思路

  • 删除左指针对应的字符,留下子串 s[low + 1:high+1]

  • 删除右指针对应的字符,留下子串 s[low:high]

    当这两个子串中至少有一个是回文串时,就说明原始字符串删除一个字符之后就以成为回文串。

image-20200519145606570

coding

class Solution:
    def validPalindrome(self, s: str) -> bool:
        #判断是否为回文
        def isvalid(temp):
            left,right = 0,len(temp)-1
            while left<right:
                if temp[left]!=temp[right]:
                    return False
                left += 1
                right -= 1
            return True

        low, high = 0, len(s) - 1
        while low < high:
            if s[low] == s[high]: 
                low += 1
                high -= 1
            else:
                return isvalid(s[low + 1: high+1]) or isvalid(s[low: high ])
        return True

时间复杂度

由暴力法的 \(O(n^2)\) 变为 \(O(n)\)

posted @ 2020-05-19 15:11  鱼与鱼  阅读(297)  评论(0编辑  收藏  举报