Valid Palindrome

leetcode:https://oj.leetcode.com/problems/

今天A了一个Easy类型的,主要是判断一个字符串是否是回文。东平西凑的还是给弄好了,具体可看下面的要求,或者直接去网站上看也行

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 public class Solution {
 2     public boolean isPalindrome(String str){
 3         char array[] = str.toCharArray();
 4         int i = 0;
 5         int j = array.length -  1;
 6         boolean isPal = true;
 7         if(str.length() == 0)
 8             return true;
 9         else if(str.length() == 1)
10             return true;
11         while(i <= j){
12             while(!isNumOrAlp(array[i++]) && i < array.length);
13             while(!isNumOrAlp(array[j--]) && j >= 0);
14             i--;
15             j++;
16             if(!isEqual(array[i], array[j]))
17             {
18                 isPal = false;
19                 break;
20             }
21             i++;
22             j--;
23         }
24         if(isPal)
25             return true;
26         
27         else        
28             return false;
29         
30     }
31     public boolean isNumOrAlp(char ch){
32         if(ch >= '0' && ch <= '9')
33             return true;
34         else if(ch >= 'a' && ch <= 'z')
35             return true;
36         else if(ch >= 'A' && ch <= 'Z')
37             return true;
38         else
39             return false;
40     }
41     public boolean isEqual(char ch1,char ch2){
42         if(0 == ch1 - ch2)
43             return true;
44         else if(32 == Math.abs(ch2 - ch1))
45             return true;
46         else if(!isNumOrAlp(ch1) && !isNumOrAlp(ch2)){
47             return true;
48         }
49         else
50             return false;
51     }
52 }

这个还是比较简单的,所以就没注释了。很多细节的地方需要注意,oj系统给出错误信息都能很好定位问题在哪儿

原文地址:https://www.cnblogs.com/luckygxf/p/4044723.html