125. Valid Palindrome 的OJ代码

iven 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.

Subscribe to see which companies asked this question.

Show Tags
Show Similar Problems

Have you met this question in a real interview? 

Yes
 


import java.util.Collections;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Solution {
    public boolean isPalindrome(String s) {
    boolean flag=false;
        //if(s==""||"".equals(s.trim())||" ".equals(s.trim())||s==" ")
        if( "".equals(s.trim()) || s.length() == 0)
        {
            flag=true;
        }
        //过滤字符
        String num = s.replaceAll("[^0-9a-zA-Z]","");
        System.out.println(num);
        String test=num.toLowerCase();//结果存放
        // System.out.println(test);


        char[] old=test.toCharArray();//转换为字符
        //String test2="";
        StringBuilder test2=new StringBuilder();
        //去掉空格
        for(int i=old.length-1;i>=0;i--){
            //test2=test2+old[i];
            test2.append(old[i]);
        }
/*        for (char c :
             test.toCharArray()) {
            test2=test2+c;
        }*/
        //String test2 = new StringBuilder(test).reverse().toString()
        //test2 = new StringBuffer(test).reverse().toString();
        System.out.println("反转后:"+test2);


        //计算出str与sb中对应位置字符相同的个数n
        int n=0;


        if(test.equals(test2.toString())){
            flag = true;
        }else {
            flag = false;
        }
/*        for(int i=0;i<test.length();i++){
            if(test.charAt(i)==test2.charAt(i) )
                n++;
        }
        //如果所有字符都相等,即n的值等于str的长度,则str就是回文。
        if(n==test.length()){
            flag=true;
        }*/
        return flag;
}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值