• LeetCode--125--验证回文串


    问题描述:

    times out:

     1 class Solution(object):
     2     def isPalindrome(self, s):
     3         """
     4         :type s: str
     5         :rtype: bool
     6         """
     7         j = len(s) - 1
     8         i = 0
     9         flag = True
    10         while i != j and flag == True:            
    11             if s[i].isalnum() and s[j].isalnum():
    12                 if s[i].lower() == s[j].lower():
    13                     flag = True       
    14                 else:
    15                     flag = False
    16             if not s[i].isalnum() :
    17                 i += 1
    18             if not s[j].isalnum():
    19                 j -= 1
    20         return flag
    21             

    错误原因:相等的时候没有移动到下一个位置

     1 class Solution(object):
     2     def isPalindrome(self, s):
     3         """
     4         :type s: str
     5         :rtype: bool
     6         """
     7         j = len(s) - 1
     8         i = 0
     9         flag = True
    10         while i < j :            
    11             if not s[i].isalnum() :
    12                 i += 1
    13                 continue
    14             if not s[j].isalnum():  
    15                 j -= 1
    16                 continue
    17             if s[i].lower() != s[j].lower():    
    18                     return False
    19             i += 1
    20             j -= 1
    21         return flag

    官方:

    1 class Solution(object):
    2     def isPalindrome(self, s):
    3         """
    4         :type s: str
    5         :rtype: bool
    6         """
    7         new_s = "".join([i for i in s if i.isalnum() or i.isalpha()]).lower()
    8         return new_s == new_s[::-1]

    正则表达式替换:

    1 class Solution(object):
    2     def isPalindrome(self, s):
    3         """
    4         :type s: str
    5         :rtype: bool
    6         """
    7         import re
    8         s = re.sub('[^a-z0-9]','',s.lower())
    9         return s == s[::-1]

    正则复习请看:http://www.runoob.com/python/python-reg-expressions.html

     视频:https://www.bilibili.com/video/av7036891?from=search&seid=10436462392778970383

    2018-09-12 19:51:17

  • 相关阅读:
    CCF CSP 201509-1 数列分段
    CCF CSP 201503-1 图像旋转 (降维)
    CCF CSP 201412-1 门禁系统
    CCF CSP 201409-1 相邻数对
    CCF CSP 201403-1 相反数
    CCF CSP 201312-1 出现次数最多的数
    Win10环境下 HTTP 错误 500.19
    牛客网 整数拆分 (动态规划)
    牛客网 放苹果
    LeetCode9 回文数
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/9636906.html
Copyright © 2020-2023  润新知