LeetCode#125. 验证回文串

题目:

LeetCode#125. 验证回文串_第1张图片

本题验证字符串s是否为回文串,在验证之前,我们首先要去掉s中包含的空格和标点符号,何以用一下代码来去除:

        c=""
        English="1234567890abcdefghijklmnopqrstuvwxyzQWERTYUIOPASDFGHJKLZXCVBNM"
        for j in s:
            if j in English:
                c+=j
        c=c.lower()

去除之后得到了新的字符串c,我们可以用Python中自带的索引切片[::-1]来简单的判断是否为回文串:

class Solution:
    def isPalindrome(self, s: str) -> bool:
        c=""
        English="1234567890abcdefghijklmnopqrstuvwxyzQWERTYUIOPASDFGHJKLZXCVBNM"
        for j in s:
            if j in English:
                c+=j
        c=c.lower()
        if c==c[::-1]:
            return True
        else:
            return False

也可以自己写出一个算法(我是根据len(c)是否为偶数来分别讨论的。):

class Solution:
    def isPalindrome(self, s: str) -> bool:
        i=0
        c=""
        English="1234567890abcdefghijklmnopqrstuvwxyzQWERTYUIOPASDFGHJKLZXCVBNM"
        for j in s:
            if j in English:
                c+=j
        c=c.lower()
        if len(c)==1 or len(c)==0:
            return True
        elif len(c)==2:
            if c[0]==c[1]:
                return True
            return False
        elif len(c)==3:
            if c[0]==c[2]:
                return True
            return False
        if len(c)%2==0:
            while i<=int(len(c)/2-1):
                if c[i]==c[len(c)-1-i]:
                    i+=1
                else:
                    return False
            return True
        else:
            while i<=int((len(c)-1)/2-1):
                if c[i]==c[len(c)-1-i]:
                    i+=1
                else:
                    return False
            return True

你可能感兴趣的:(LeetCode,leetcode,算法)