JonnyF--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.

解题思路

      验证一个字符串是否是回文字符串。因此在这里我使用的方式是首先判断字符串中的每个字符是否是在A~Z,a~z,0~9中的,如果存在就添加在新的数组中,然后将新数组中的全部元素统一转变为小写,然后将新数组一分为二,逐个对比看是否相同,如果有不同就返回False,否则就说明这个字符串为回文。

class Solution:
    # @param s, a string
    # @return a boolean
    def isPalindrome(self, s):
        if s == '':
            return True
        else:
            sTmp = ''
            for i in range(0, len(s)):
                if s[i] >= 'a' and s[i] <= 'z' or s[i] >= '0' and s[i] <= '9' or s[i] >= 'A' and s[i] <= 'Z':
                    sTmp += s[i]
            sTmp = sTmp.lower()
            for i in range(0, len(sTmp)/2):
                if sTmp[i] != sTmp[len(sTmp)-1-i]:
                    return False
            return True
posted @ 2015-05-11 17:28  F-happy  阅读(111)  评论(0)    收藏  举报