Valid Palindrome(LintCode)

Valid Palindrome

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
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.

Challenge

O(n) time without extra memory.

 

深刻体会到了英文的用处。。。题目的中文翻译真是误导人。

 1 public class Solution {
 2     /**
 3      * @param s A string
 4      * @return Whether the string is a valid palindrome
 5      */
 6     public boolean isPalindrome(String s) {
 7         char[] cs = s.toCharArray();
 8         int i = 0;
 9         int j = cs.length - 1;
10         
11         while(i<j) {
12             while(i<j && !Character.isDigit(cs[i]) && !Character.isLetter(cs[i])) i++;
13             while(i<j && !Character.isDigit(cs[j]) && !Character.isLetter(cs[j])) j--;
14             if(i >= j) break;
15             String ss = cs[i] + "";
16             String ss1 = cs[j] + "";
17             if(!ss.equalsIgnoreCase(ss1)) 
18                 return false;
19                 
20             i++;
21             j--;
22         }
23         return true;
24     }
25 }
View Code

 

posted @ 2015-12-06 16:01  -.-|  阅读(146)  评论(0编辑  收藏  举报