leetcode_125. Valid Palindrome 判断字母数字回文串,大小写转化

来源:互联网 发布:文笔比较好的网络作者 编辑:程序博客网 时间:2024/05/18 02:18

题目:

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.


题意:

给定一个字符串,判断是否是字母数字回文串,即忽略大小写,只考虑字母、数字的字符串是否为回文串。


代码:

class Solution(object):
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        
        len_s = len(s)
        
        if len_s == 0 :
            return True
        else :
            s_list = []
            for i in range(len_s) :            #将字符串去掉除字母、数字之外的字符,存在list中
                if ord(s[i]) <= ord('z') and  ord(s[i]) >= ord('a') :
                    s_list.append(s[i])
                else :
                    if  ord(s[i]) <= ord('Z') and  ord(s[i]) >= ord('A') :         #大写转化为小写
                        s_list.append(s[i].lower())                  
                    else :
                        if  ord(s[i]) <= ord('9') and  ord(s[i]) >= ord('0') :
                            s_list.append(s[i])
            
            n = len(s_list)
            for i in range(n/2) :                 #判断是否为回文串
                if s_list[i] != s_list[n-1-i] :
                    return False
            
            return True
               

笔记:

1、字符转化为ASCLL码:ord('A')

2、ASCLL码转化为字符:chr(65)

3、大写转小写:‘A’.lower()

4、小写转大写:'a'.upper()



0 0
原创粉丝点击