1. 程式人生 > >[LeetCode] 125. Valid Palindrome Java

[LeetCode] 125. Valid Palindrome Java

是否 eric case side uil for als bool ace

題目:

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.

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.

題意及分析:給出一個字符串,只考慮其中的字母或者數字字符,問字符串是否是一個回文,註意空字符串也是回文。

方法一:先遍歷一次字符串去除非數字字母字符,然後判斷是否是回文,復雜度為n+n/2

class Solution {
    public boolean isPalindrome(String s) {
        if(s == null || s.length() == 0 ) return true;

        StringBuilder sb 
= new StringBuilder(); for(int i=0;i<s.length();i++){ //取出標點符號,只留下字母 char ch = s.charAt(i); if(Character.isLetterOrDigit(ch)){ sb.append(ch); } } //全部變為小寫字母 String newStr = sb.toString().toLowerCase(); for
(int i=0;i<newStr.length()/2;i++){ if(newStr.charAt(i)!=newStr.charAt(newStr.length()-1-i)) return false; } return true; } }

方法二:直接判斷,每次分別從前和從後找到一個字母數字字符,若不相等直接返回false,復雜度最多為n

class Solution {
    public boolean isPalindrome(String s) {
        if(s == null || s.length() == 0 ) return true;
        int i = 0,j = s.length()-1;
        for(i=0,j=s.length()-1;i<j;++i,--j){
            while(i<j && !Character.isLetterOrDigit(s.charAt(i))) i++;
            while(i<j && !Character.isLetterOrDigit(s.charAt(j))) j--;
            if(i<j && Character.toLowerCase(s.charAt(i))!=Character.toLowerCase(s.charAt(j))) return false;
        }
        return true;
    }
}

[LeetCode] 125. Valid Palindrome Java