[125] 验证回文串

2020-06-28  本文已影响0人  阳明先生_X自主

https://leetcode.com/problems/valid-palindrome/
第一步验证只有数字和字母,
第二步字符串反转
第三步比较是否相等

# -*- coding: utf-8 -*
# @lc app=leetcode.cn id=125 lang=python3
#
# [125] 验证回文串
#

# @lc code=start
# class Solution:
#     def isPalindrome(self, s: str) -> bool:
#       s = [i for i in s.lower() if i.isalnum()]
#       return s == s[::-1]    
class Solution:
    def isPalindrome(self, s: str) -> bool:
        i, j = 0, len(s) - 1
        while i < j:
            a, b = s[i].lower(), s[j].lower()
            if a.isalnum() and b.isalnum():
                if a != b: return False
                else:
                    i, j = i + 1, j - 1
                    continue
            i, j = i + (not a.isalnum()), j - (not b.isalnum())
        return True
上一篇 下一篇

猜你喜欢

热点阅读