[LeetCode]125. Valid Palindrome ★

题目描述

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Note: For the purpose of this problem, we define empty string as valid palindrome.
题目大意:给定一个字符串,字符串中只有英文字母、空格和标点符号,请判断该字符串是否是回文串,判断的时候只考虑英文字母是否回文且忽略大小写。

样例

Example 1:

Input: “A man, a plan, a canal: Panama”
Output: true

Example 2:

Input: “race a car”
Output: false

python解法

class Solution:
    def isPalindrome(self, s: str) -> bool:
        s = s.lower()
        trantab = str.maketrans({key: None for key in string.punctuation})
        s = s.translate(trantab)
        s = s.replace(' ','')
        if s == ''.join(reversed(s)):
            return True
        else:
            return False

Runtime: 48 ms, faster than 88.45% of Python3 online submissions for Valid Palindrome.
Memory Usage: 14.7 MB, less than 15.47% of Python3 online submissions for Valid Palindrome.
题后反思:

  1. 第一次用到这种字符串的替换方式,写一写我看到的这些方法的用法
  2. str中的maketrans方法用于构造一个可以用于translate方法使用的表,它有三个参数,后两个可选,如果只有一个参数,必须以字典的形式给出,如程序中所示,代表标点符号替换成None;如果使用两个参数,那么两个参数之间的字符串长度必须一致,两者之间代表一个映射关系;如果使用三个参数,那么除了映射关系之外,还加上了删除特定字符的功能
  3. 删除标点符号之后,字符串中还有空格,所以使用replace函数将空格去掉了。其实可以在构造trantab的时候加上空格的映射,这样replace方法就省了。
  4. 字符串的replace方法不改变原来字符串。

C语言解法

bool isPalindrome(char * s){
    if (!strlen(s))
    {
        return true;
    }
    char * str = (char*)malloc(sizeof(s[0])*strlen(s));
    int len = 0;
    int i=0;
    while(s[i]!='\0')
    {
        if (s[i]>='A'&&s[i]<='Z')
        {
            str[len++] = s[i]+0x20;
        }
        else if (s[i]>='a'&&s[i]<='z' || s[i] >= '0' && s[i] <= '9')
        {
            str[len++] = s[i];
        }
        i ++;
    }
    for (int i = 0;i<len/2;i++)
    {
        if (str[i] != str[len-i-1])
        {
            free(str);
            return false;
        }
    }
    free(str);
    return true;
}

Runtime: 4 ms
Memory Usage: 7.8 MB
题后反思:

  1. 原本在求数组s的长度时直接使用sizeof(s),但是求出来的结果是错误,通过上网查找,找到以下原因:
  • 在c中,数组在作为参数的时候就退化为指针,对一个地址来取大小呢,如果是32位系统的话即为4,如果是64位系统的话为8,所以呢,在函数中sizeof获取的是指针的长度而不是数组的长度。
  • 在函数中,sizeof的处理时间的在编译期,也就是说对于动态生成的数组大小是不能用sizeof来算出来的。

文中都是我个人的理解,如有错误的地方欢迎下方评论告诉我,我及时更正,大家共同进步

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值