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

算法思路:总的来说这道题还是比较简单的,首先动态创建两个StringBuffer两个类,然后把String的内容按照数字字母(把大写变成小写,小写不变)通过用append()方法分别加入到StringBuffer sb ,StringBuffer str 中,然后利用reverse()方法反转sb,然后通过toString()把StringBuffer类变成String类,最后用equals()对 sb 和 str 进行比较,如果相等就是回文,返回 true,如果不相等返回false。

注意:1.要想用equals 进行字符串比较,首先把StringBuffer变成Sting,用toString()方法

           2.把sb 反转后 也就是说sb.reverse = sb,他们都是反转过后的字符串,所以相等。

最后附上自己的代码

class Solution {
    public boolean isPalindrome(String s) {
        if(s.length() == 0 || s.length() == 1) return true;
        StringBuffer sb = new StringBuffer();
        StringBuffer str = new StringBuffer();
        char [] ch = s.toCharArray();
        for(int i = 0; i < ch.length; i++){
            if((ch[i] >= 97 && ch[i] <= 122) || (ch[i] >= 48 && ch[i] <= 57)){
                sb.append(ch[i]);
                str.append(ch[i]);
            }
            else if(ch[i] >= 65 && ch[i] <= 90){
                sb.append(Character.toLowerCase(ch[i]));
                str.append(Character.toLowerCase(ch[i]));
            }
        }
        if(str.reverse().toString().equals(sb.toString())) return true;//注意细节
        else return false;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值