【LeetCode】125、Valid Palindrome

1、题目描述:

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? is is a good question to ask during an
interview.

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

2.1、可以看出标点符号、空格是舍去不计的,大小写之间是没有差别的、大写小写字母之间需要相互转化。

2.2、知识点:如果我们不是以除正常方式以外的其他任意方式退出循环(即满足前面的循环结束条件,正常循环结束,执行else),那么else分支将被执行。也就是在循环体内没有break语句、没有return语句,或者没有异常出现,则将会执行else。

2.3、可看出,return语句执行后也是跳出(结束)循环了。


可以记忆为:for else是一体的结构,break跳出这整个结构当然不会执行结构内部的else语句。

3、解答:Python strip() 方法用于移除字符串头尾指定的字符(默认为空格,且需注意只能移除首尾指定的字符);

                  ASCII码和数字之间的转化: ord('a') 和chr(59) 。ord函数利用字符求得ASCII数字,chr函数利用ASCII数字求得字符;

                  大小写字母的取值范围是,其他不在此范围之内的都不是字母(48-57: "0"--"9";  65-90: "A"--"Z";  97-122: "a"--"z");

                  参见:http://blog.csdn.net/mtbaby/article/details/54907454

                  大小写之间的相互转化有upper() 、lower() 函数;判断字符是否是字母(isalpha())、数字(isdigit())、字母加数字(isalnum())

class Solution:
    # @param s, a string
    # @return a boolean
    def isPalindrome(self, s):
        newS= [i.lower() for i in s if i.isalnum()]
        #return newS == newS[::-1]
        return newS[:len(newS)/2] == newS[(len(newS)+1)/2:][::-1]
 
另一种代码:
class Solution(object):
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """ 
        start = 0
        end = len(s)-1
        while start < end:
            while start < end and not s[start].isdigit() and not s[start].isalpha():
                start += 1
            while start < end and not s[end].isdigit() and not s[end].isalpha():
                end -=1
            if s[start].lower() != s[end].lower():
                return False
            start += 1
            end -= 1
        else:
            return True


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值