Valid Palindrome

来源:互联网 发布:淘宝cos道具定制店 编辑:程序博客网 时间:2024/06/09 19:17
125. Valid Palindrome
given: a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
e.g. 
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.


Note:
for this case, empty string is also a valid palindrome.
strategy 
1. using two point to track the char in the two end of string
2. using lang.Character.isLetterOrDigit() method to return true if the char is a letter or digit, false otherwise.
    if it is false, increment the index of char in the string array
3. compare the char from the start and the end of the string by converting all char into lowercase. if it is false, return 
   false for the method. if it is true, increment the start end and decrement the terminal end and repeat 2 and 3
4. until the start end no less than terminal end.


public class Solution{
    public boolean isPalindrome(String s){
        int start=0, end=s.length()-1;
        while (start < end){
             while(start < end&&!Character.isLetterOrDigit(s.charAt(start))){
                  start++;
             }
             while(start < end&&!Character.isLetterOrDigit(s.charAt(end))){
                   end--;
             }
             if(Character.toLowerCase(s.charAt(start))!=Character.toLowerCase(s.charAt(end))){
                 return false;
             }
             start++; 
             end--;
         }
         return true;
     }
}
0 0
原创粉丝点击