LeetCode OJ - Valid Palindrome

字符串回文验证:简单高效的方法

这道题挺简单的,但是需要细心。

最好的方法是先对string做预处理,然后再判断是否是回文。

下面是AC代码:

 1 /**
 2      * Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
 3      * @param s
 4      * @return
 5      */
 6     public boolean isPalindrome(String s){
 7         String pre = preProcess(s);
 8         char[] sw = pre.toCharArray();
 9         if(pre==null || pre.length()<=1 )
10             return true;
11         int i=0;
12         int j=pre.length()-1;
13         while(i<=j){
14             if(sw[i]!=sw[j])
15                 return false;
16             i++;
17             j--;
18         }
19         return true;
20     }
21     /**
22      * pre-processing the string, remove all non-isAlphanumeric
23      * and change all to lower
24      * @param s
25      * @return
26      */
27     private String preProcess(String s){
28         
29         StringBuffer sb = new StringBuffer();
30         for(int i=0;i<s.length();i++)
31             if(isAlphanumeric(s.charAt(i)))
32                 sb.append(s.charAt(i));
33         return sb.toString().toLowerCase();
34     }
35     /**
36      * make decision if a character is a alphanumeric
37      * @param c
38      * @return
39      */
40     private boolean isAlphanumeric(char c){
41         if(c>='a' && c<='z' || c>='A' && c<='Z' || c>='0'&& c<='9')
42             return true;
43         return false;
44     }

 

转载于:https://www.cnblogs.com/echoht/p/3701100.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值