码迷,mamicode.com
首页 > 其他好文 > 详细

125. Valid Palindrome

时间:2016-06-25 12:17:47      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

题目:

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.

Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.

For the purpose of this problem, we define empty string as valid palindrome.

链接: http://leetcode.com/problems/valid-palindrome/

一刷,用两个指针从两个方向,出现的问题

1. string methods掌握不熟,str.isalpha(), str.isdigit(), str.isalnum()

2. 内部两个while loop之后需要再检查index是否valid,否则或者应该跳到外循环检查

3. 不要忘记更新下标

class Solution(object):
    def isPalindrome(self, s):
        if not s or s == ‘‘:
            return True
        i, j = 0, len(s) - 1
        
        while i <= j:
            while i < len(s) and not s[i].isalnum():
                i += 1
            while j >= 0 and not s[j].isalnum():
                j -= 1
            if i == len(s) or j < 0:
                break
            if s[i].isalpha() and s[j].isalpha() and s[i].lower() == s[j].lower() or s[i].isdigit() and s[j].isdigit() and s[i] == s[j]:
                pass
            else:
                return False
            i += 1
            j -= 1
        return True

对比相同方法别人的代码,可以有以下改动:

class Solution(object):
    def isPalindrome(self, s):
        i, j = 0, len(s) - 1
        while i <= j:
            while i < j and not s[i].isalnum():
                i += 1
            while i < j and not s[j].isalnum():
                j -= 1
            if s[i].lower() != s[j].lower():
                return False
            i += 1
            j -= 1
        return True

别人还有更pythonic但是需要额外空间复杂度的做法,很赞,平时工作完全能写得出,但是刷题时就忘记了:

class Solution(object):
    def isPalindrome(self, s):
        cleanlist = [c for c in s.lower() if c.isalnum()]
        return cleanlist == cleanlist[::-1]

 

125. Valid Palindrome

标签:

原文地址:http://www.cnblogs.com/panini/p/5615978.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!