125. Valid Palindromec [验证回文串]

71 篇文章 0 订阅
22 篇文章 0 订阅
  • 回文串

正读和反读都一样的字符串,比如“level”或者“noon”或者"a"

描述

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.

给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串

例子
在这里插入图片描述

思路

  • 双指针法
  • 先把字符串变成有效字符串,再验证是否为回文
    答案
  • java
class Solution {
    public boolean isPalindrome(String s) {
        
        StringBuilder sb = new StringBuilder();
        
        for(int i=0; i<s.length(); i++) {
            char c = s.charAt(i);
            if(c>='0' && c<='9') sb.append(c);
            if(c>='a' && c<='z') sb.append(c);
            if(c>='A' && c<='Z') sb.append((char)(c+32));
        }
        
        int i=0,j=sb.length()-1;
        while(i<j) {
            if(sb.charAt(i)!=sb.charAt(j)) return false;
            i++;
            j--;
        }
       
        
        return true;
    }
}
  • python
def isPalindrome(self, s: str) -> bool:
        i=0
        j = len(s)-1
        while i<j: #当字符串为"a"时,直接略过该while,返回True,见下
            if not s[i].isalnum():
                i +=1
                continue
            if not s[j].isalnum():
                j -= 1
                continue
            if s[i].lower()==s[j].lower():
                i += 1
                j -= 1
            else:
                return False
        
        return True
  • c++
   bool isPalindrome(string s) {
        int i=0,j=s.size()-1;
        
        while (i<j)//当字符串为"a"时,直接略过该while,返回True,见下
        {
            if (!isalnum(s[i]))
            {
                i++;
                continue;
            }
            if (!isalnum(s[j]))
            {
                j--;
                continue;
            }
            if (tolower(s[i])==tolower(s[j]))
            {
                i++;
                j--;
            }
            else
                return false;
                
        }
        
        return true;
        
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值