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

  • 相关阅读:
    C/C++ 知识点---存储区
    Objective-C中的@property和@synthesize用法
    C/C++ 知识点---数组与指针
    C/C++ 知识点---C语言关键字(32个)
    js里json和eval()
    js--冒泡排序
    js数学公式-曲线运动
    事件绑定兼容(事件流的机制;事件委托
    2 获取元素在页面中的位置
    Dom关于位置和尺寸的api
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/9636906.html
Copyright © 2011-2022 走看看