zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    虚拟机设置与主机同网段的IP
    centos8 安装docker
    postgresql10 修改密码及远程访问
    centos7 安装pycharm
    centos7安装Python
    docker容器固定ip
    centos7 redis 自启动
    centos7 nginx添加自启
    docker 容器时间不正确的修改方法
    浅谈麦克斯韦方程组与相对论
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/9636906.html
Copyright © 2011-2022 走看看