Valid Palindrome(easy)

来源:互联网 发布:淘宝双11红包怎么领 编辑:程序博客网 时间:2024/05/15 11:50

【题目】

      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 isValid(char c){        if(c >= 'a' && c <= 'z') return true;        if(c >= '0' && c <= '9') return true;        return false;    }    public boolean isPalindrome(String s) {        // Start typing your Java solution below        // DO NOT write main() function        if(s.equals("")) return true;        s = s.toLowerCase();        int len = s.length();        int left = 0, right = len - 1;        while(left < right){            while(!isValid(s.charAt(left))){                left++;                if(left >= right) return true;            }             while(!isValid(s.charAt(right))){                right--;                if(left >= right) return true;            }            if(s.charAt(left) != s.charAt(right)) return false;            left++;            right--;        }        return true;}}


0 0
原创粉丝点击