Monday, June 9, 2014

Valid Palindrome

This question is quite easy I believe. First step I take is to pre-process the string, eliminate characters except alphanumerical ones. Method prc is responsible for this work.

public class Solution {
    public boolean isPalindrome(String s) {
        if(s == null) return true;
        String lowCase = s.toLowerCase();
        String prcdS = prc(lowCase);
        if(prcdS.length() < 2) return true;
        int i = 0;
        int j = prcdS.length() - 1;
       
        while(i<j){// check whether the processed string is palindrome
            if(prcdS.charAt(i) != prcdS.charAt(j)) return false;
            i++;
            j--;
        }
        return true;
    }
   
    public String prc(String s){
        StringBuffer result = new StringBuffer();
        for(int i = 0; i < s.length(); i ++){
            if((s.charAt(i) >= 'a' && s.charAt(i) <= 'z')||(s.charAt(i) >= '0' && s.charAt(i) <= '9')) result.append(s.charAt(i));
        }
       
        return result.toString();
    }
}

No comments:

Post a Comment