搜索此博客

2013年1月27日星期日

Valid Palindrome


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.
01 public boolean isPalindrome(String s) {
02     if(s=="") return true;
03     char[] str=s.toCharArray();
04     if(str.length==1) return true;
05     int start=0, end=str.length-1;
06     while(start<end)
07     {
08         while(start<str.length && !isAlphanumeric(str[start]))  start++;
09         while(end>= 0 && !isAlphanumeric(str[end])) end--;
10         if(start>=end)  return true;
11         if(!isEqual(str[start],str[end]))
12         {
13             return false;
14         }
15         start++;
16         end--;
17     }
18     return true;
19   
20 }
21 public boolean isAlphanumeric(char c)
22 {
23     return isLetter(c)||isNumber(c);
24 }
25 public boolean isLetter(char c)
26 {
27     if(c>='a' && c<='z' ||c>='A' && c<='Z')
28         return true;
29     else
30         return false;
31 }
32 public boolean isNumber(char c)
33 {
34     if(c>='0' && c<='9') return true;
35     else return false;
36 }
37 
38 public boolean isEqual(char a, char b)
39 {
40     if(isLetter(a) && isLetter(b) && Character.toUpperCase(a)==Character.toUpperCase(b))
41         return true;
42     else if(isNumber(a) && isNumber(b) && a==b)
43         return true;
44     else
45         return false;
46 }

没有评论:

发表评论