zoukankan      html  css  js  c++  java
  • [leetcode] Valid Palindrome @ Python

    原题地址:https://oj.leetcode.com/problems/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

    "radar" is a palindrome

    "rotator" 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.

    解题思路1:利用python的list comprehension 以及string 的 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] 

    需要说明的是程序的最后一行对于newS长度为奇或者为偶都通用

    newS[:len(newS)/2] == newS[(len(newS)+1)/2:][::-1]

    解题思路2:将不是字母的字符去掉,然后转换成小写,然后简单的回文判断。

    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

     参考致谢:

    [1]http://www.cnblogs.com/zuoyuan/p/3765882.html

  • 相关阅读:
    【?】Hello。。。
    【Calc】对于‘精分’的研究
    [AFO]记五年oi生涯及CSP2019复赛游记
    CF#579div.3
    「BZOJ1827」奶牛大集会
    「BZOJ2821」作诗 && 「BZOJ2724」蒲公英
    「BZOJ4576」262144
    「Bzoj5055」膜法师
    「51nod1689」逛街
    「51nod1681」公共祖先 &&「51nod2553」双重祖先
  • 原文地址:https://www.cnblogs.com/asrman/p/3974114.html
Copyright © 2011-2022 走看看