[leetcode] 125. Valid Palindrome

题目描述:

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.

题意:

判断去除空格和标点后的字符串是否为回文,即所谓的有效回文判断。

python代码:

class Solution:
    # @param {string} s A string
    # @return {boolean} Whether the string is a valid palindrome
    def isPalindrome(self, s):
        start, end = 0, len(s) - 1
        while start < end:
            while start < end and not s[start].isalpha() and not s[start].isdigit():
                start += 1
            while start < end and not s[end].isalpha() and not s[end].isdigit():
                end -= 1
            if start < end and s[start].lower() != s[end].lower():
                return False
            start += 1
            end -= 1
        return True

Python isalpha()方法

描述:检测字符串是否只由字母组成。
参数:
返回值:如果字符串至少有一个字符并且所有字符都是字母则返回True,否则返回 False

Python isdigit()方法

**描述:**Python isdigit() 方法检测字符串是否只由数字组成。
**语法:**str.isdigit()
参数:无。
返回值:如果字符串只包含数字则返回 True 否则返回 False。

程序思路:逐个判断,如果不是字母或者数字就移动start和end指针;否则判断两指针对应的字符是否相同,从而判断是否为回文。

我的代码:

class Solution(object):
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """

        from string import punctuation
        # s = s.replace(s.punctuation,"")
        # s.translate(None, punctuation)
        s = "".join(s.split())
        s = "".join([c for c in s if c not in punctuation])
        start = 0
        end = len(s) - 1
        if start == end:
            return True
        while start < end:
            if s[start].lower() == s[end].lower():
                start = start + 1
                end = end - 1
            else:
                return False
        return True

我的思路是先去掉空格和标点符号。由于去掉空格和标点符号都要对字符串进行一次遍历,所以复杂度就高了T^T。
不过这里还学了挺多的,比如怎么去掉空格和标点符号,还有python是大小写敏感的,就需要转换一下[用upper(),lower()]才可以比较。

知识补充:

字符串去掉标点符号:
参考:http://www.itstrike.cn/Question/5860b8a2-6c44-44f4-8726-c5a7603d44cc.html

  • 使用str.translate:
from string import punctuation
[ x.translate(None, punctuation) for x in lis]
from string import punctuation
strs.translate(None, punctuation)
  • 使用正则表达式:
import re
[ re.sub(r'[{}]+'.format(punctuation),'',x ) for x in lis]
re.sub(r'[{}]+'.format(punctuation),'', strs)
  • 使用list的comprehension和str.join:
["".join([c for c in x if c not in punctuation]) for x in lis]
"".join([c for c in strs if c not in punctuation])

其实还是有点问题的,因为用的前两种,好像编译时候还是不行。
使用translate时候会提醒translate只需要一个参数。好吧,还是需要看看python学习手册。慢慢解决。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值