1. 程式人生 > >Valid Palindrome

Valid Palindrome

info default nbsp borde == left pos post ive

Valid Palindrome

Total Accepted: 22728 Total Submissions: 99271My Submissions

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.


public class Solution {
    public boolean isPalindrome(String s) {
        if (s == null) {
            return false;
        }
        if (s.length() == 0 || s.length() == 1) {
            return true;
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length();i++){
            Character ch = s.charAt(i);
	            if(Character.isLetter(ch) || Character.isDigit(ch)){
                sb.append(Character.toUpperCase(ch));

            } else {
                continue;
            }
        }
        int start = 0 ;
        int end = sb.length() - 1;
        while ( start < end) {
            if (sb.charAt(start) == sb.charAt(end)) {
                start ++;
                end --;
            } else {
                return false; 
            }
        }
        return true;
     }
}

這個題目的問題在於剛開始的時候沒有考慮到可能是數字的情況。題目本身沒有難度。

Valid Palindrome