leetcode——125.验证回文串

class Solution:
    def isPalindrome(self, s: str) -> bool:
        import re
        from string import punctuation
        add_punc="' '"
        all_punc=add_punc+punctuation
        b=''.join(i for i in s if i not in all_punc)
        c=b.lower()
        if c=='' or len(c)==1:
            return True
        if len(c)==2:
            return c[0]==c[1]
        if len(c)%2==1:#长度是奇数
            return list(c[:len(c)//2])==list(reversed(c[len(c)//2+1:]))
        else:
            return list(c[:len(c)//2])==list(reversed(c[len(c)//2:]))
执行用时 :56 ms, 在所有 Python3 提交中击败了93.35%的用户
内存消耗 :14.3 MB, 在所有 Python3 提交中击败了29.68%的用户
 
用到了字符串的连接方式:
b=''.join(i for i in s if i not in all_punc)
用到了
        from string import punctuation
        add_punc="' '"
        all_punc=add_punc+punctuation

别人28ms的范例:

class Solution:
    def isPalindrome(self, s: str) -> bool:
        if not s:
            return True
        s = s.lower()
        s = re.sub(r'\W+', '', s)
        return s == s[::-1]

这里面用到了:

s = re.sub(r'\W+', '', s)

其中

re.sub用于实现正则的替换
\W+ 匹配非字母数字及下划线。,

除此之外,人家直接返回

s == s[::-1]

比我的做法要简洁的多。

改正如下:

class Solution:
    def isPalindrome(self, s: str) -> bool:
        import re
        from string import punctuation
        add_punc="' '"
        all_punc=add_punc+punctuation
        b=''.join(i for i in s if i not in all_punc)
        c=b.lower()
        if c=='' :
            return True
        else:
            return c==c[::-1]
执行用时 :48 ms, 在所有 Python3 提交中击败了98.64%的用户
内存消耗 :14.4 MB, 在所有 Python3 提交中击败了26.78%的用户
 
正则表达式牛逼!!!!
                                                                                            ——2019.10.9
 

复习,没有用到正则表达式
效果并不是很好。
public boolean isPalindrome(String s) {  //只考虑字母和字符
        String s1 = s.toLowerCase();
        String[] list_s = s1.split(" ");
        s = String.join("",list_s);  //将字符串拼接起来,消除空格
        int i = 0,j = s.length()-1;
        while(i<=j){
            if(s.charAt(i) == s.charAt(j)){
                i++;
                j--;
            }else if(s.charAt(i) < 48||(s.charAt(i) > 57 &&s.charAt(i)<97) || s.charAt(i) > 122){
                i++;
            }else if(s.charAt(j) < 48||s.charAt(j) > 57 &&s.charAt(j)<97 || s.charAt(j) > 122){
                j--;
            }else{
                return false;
            }
        }
        return true;
    }

 

 

和那些优秀例子相比,思路是一样的,但是处理的时候,我将字符转换成了数字进行比较,但是人家直接是比较字符,不知道是不是因为这个原因所以人家会快一点。

就还是加油吧。

 ——2020.7.6

 

posted @ 2019-10-09 16:26  欣姐姐  阅读(150)  评论(0编辑  收藏  举报