2020年6月18日 【LeetCode每日一题】2020.6.19 125. 验证回文串

125. 验证回文串

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

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

示例:

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

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

分析:

​ 可以利用双指针来判断。

​ (1)可以先对数据做预处理,但是会占用额外空间。

new_s = "".join(ch.lower() for ch in s if ch.isalnum())
left, right = 0, n - 1
while left < right:
    if s[left] != s[right]:
        return False
return True

​ (2)直接对原数组做修改。

left, right = 0, n - 1
while left < right:
    while left < right and not s[left].isalnum():
        left += 1
    while left < right and not s[right].isalnum():
        right -= 1
    if left < right:
        if s[left].lower() != s[right].lower():
            return False
       	left += 1
        right -= 1
return False

代码(Python):

class Solution:
    def isPalindrome(self, s: str) -> bool:
        """
        进行预处理
        """
        string= "".join(ch.lower() for ch in s if ch.isalnum())
        n = len(string)
        left, right = 0, n - 1
        while left < right:
            if string[left] != string[right]:
                return False
            left += 1
            right -= 1
        return True  

猜你喜欢

转载自www.cnblogs.com/enmac/p/13161229.html