125. Valid Palindrome(回文)

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Note: For the purpose of this problem, we define empty string as valid palindrome.

Example 1:

Input: “A man, a plan, a canal: Panama”
Output: true
Example 2:

Input: “race a car”
Output: false

class Solution {
     public boolean isPalindrome(String s) {

            s = s.replaceAll("[^a-zA-Z]", "").toLowerCase();
//         Stack<Character> stack = new Stack();
//         for(int i=0; i<s.length();i++){
//             stack.push( s.charAt(i) );
//         }
        
//          for(int j=0; j<s.length();j++){
//             char cTmp = stack.pop();
//              // System.out.println("cTmp"+cTmp);
//            //  System.out.println("cTmp"+s.charAt(i));
//              if(cTmp != s.charAt(j) ){                 
//                  return false;
//              }
//         }
        
//         return true;


         s = s.toLowerCase();
         char [] charArray = s.toCharArray();
         String temp = "";
         for(int i=0;i<charArray.length;i++)
         {
             if( ((int)charArray[i] >= 48 && (int)charArray[i] <= 57) || ((int)charArray[i] >= 97 && (int)charArray[i] <= 122))
            {
                temp += charArray[i];
            }
        }
        char [] resultArray = temp.toCharArray();
        int begin = 0;int end = resultArray.length - 1;
        while(begin < end)
        {
            if(resultArray[begin] == resultArray[end])
            {
               begin++;
                end--;
            }else{
                return false;
            }
        }
        return true;
     }
}

猜你喜欢

转载自blog.csdn.net/touhou8775/article/details/84671915