Leetcode#125. 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.

题意

给你一个字符串,判断是否为回文字符串。
回文字符串的定义:
只比较数字和字符,忽略其他字符,不考虑字符大小写。

题解

  1. 把字符串中的字符全部转换为小写字符。
  2. 拿左边的元素和右面的元素比较。会出现三种情况
    1. 左边字符不属于数字和字符,跳到左边下一个。
    2. 右边字符不属于数字和字符,跳到右边下一个。
    3. 左右字符均合法,比较两字符是否相同:
      1. 相同,左右同时跳到下一个
      2. 不同,直接结束,可以判断此字符串不是合法的回文串。
      1. 左边指针指向大于右边指针指向,结束,为合法的回文串。
Python语言
class Solution(object):
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """

        s = s.lower(); #字母全部转换为小写
        start = 0
        end = len(s)-1
        if len(s)==0 or len(s)==1:
            return True

        while start<=end: #同时从比较左右对应元素是否相同
            if (s[start]<"a" or s[start] > "z") and (s[start] < "0" or s[start] > "9"): #左边的元素既不是字符又不是数组,跳到下一个
                start = start + 1
            elif (s[end]<"a" or s[end] > "z") and (s[end] < "0" or s[end] > "9"):#同样处理右边的元素
                end = end - 1
            else:
                if s[start] == s[end]:#相同比较下一个
                    start = start + 1
                    end = end - 1
                else:#只有一出现不相同的即不为回文字符串 
                    return False

        return True
C++语言
class Solution {
public:
    bool isPalindrome(string s) {
        int start = 0;
        int end = s.length() - 1;
        string temp = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        if(s.length()==0||s.length()==1)
            return true;
        while(start <= end)
        {
            if(temp.find(s[start])<0||temp.find(s[start])>61)
               start++;
            else if(temp.find(s[end])<0||temp.find(s[end])>61)
                end--;
            else
            {
                if(((s[start]-32==s[end] || s[start]+32==s[end])&&(temp.find(s[start])>=0&&temp.find(s[start])<=51&&temp.find(s[end])>=0&&temp.find(s[end])<=51)) || s[start] == s[end])
                {
                    start++;
                    end--;
                }
                else
                    return false;
            }
        }
        return true;
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值