首页 > 其他 > 详细

LeetCode(125):Valid Palindrome

时间:2016-01-08 00:22:11      阅读:166      评论:0      收藏:0      [点我收藏+]

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;
            
        }
}

结果:

技术分享

LeetCode(125):Valid Palindrome

原文:http://www.cnblogs.com/Lewisr/p/5111598.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!