• 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

  • 相关阅读:
    django查询今天,昨天,一周,分组统计月,年
    Rancher2.4.3 Rest API修改镜像地址
    Django-filter实现动态过滤与排序
    Python实现随机生成头像
    Python项目目录结构
    Django继承AbstractUser扩展字段
    Celery 监控方案
    Django项目配置快速启动
    Docker镜像分析工具dive
    Ddjango 多个app的urls配置
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/9636906.html
Copyright © 2020-2023  润新知