LeetCode(125):Valid Palindrome

Valid Palindrome: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.

题意:判断给定的字符串是否为回文。回文,亦称回环,是正读反读都能读通的句子,亦有将文字排列成圆圈者。

思路:通过从前后两个方向来判断是否为回文。本题中有效的字符是字母和数字,并且忽略字母的大小写。

代码:

public class Solution {
    //判断是否为小写、大写、数字
    public boolean isalpha(char c){
        if('a' <= c && c <= 'z') return true;  
        if('A' <= c && c <= 'Z') return true;  
        if('0' <= c && c <= '9') return true;  
        return false;  
    }
    //将大写转换为小写
    public char tolower(char c){
         if ((c>='A'&&c<='Z')){
             return c = (char) (c-'A' + 'a');
         }
        return c;
     }
    public boolean isPalindrome(String s) {
            int n = s.length();
            int i = 0,j= n - 1;
            while(i<j){
                if(!isalpha(s.charAt(i))){
                    i++;
                    continue;
                }
                if(!isalpha(s.charAt(j))){
                    j--;
                    continue;
                }
                if(tolower(s.charAt(i))!=tolower(s.charAt(j))) 
                return false;
                ++i;--j;
            }
            return true;
            
        }
}

结果:

QQ截图20160107225415

原文地址:https://www.cnblogs.com/Lewisr/p/5111598.html