LeetCode之验证回文串

给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。

说明:本题中,我们将空字符串定义为有效的回文串。

示例 1:

输入: "A man, a plan, a canal: Panama"
输出: true

示例 2:

输入: "race a car"
输出: false

自己的low货代码

 public boolean isPalindrome(String s) {
        if (s.length()==0||s == null){
            return true;
        }
        s=s.toLowerCase();
        int left = 0;
        int right = s.length() - 1;
        while(left<right){
            while(left<right&&!Character.isLetterOrDigit(s.charAt(left))){
                left++;
            }
            while(left<right&&!Character.isLetterOrDigit(s.charAt(right))){
                right--;
            }
            if(left<right&&s.charAt(left)==s.charAt(right)){
                left++;
                right--;
            }else if(left<right) {
                return false;
            }
        }
        return true;
        }

参考过大神代码之后的改进

public boolean isPalindrome(String s) {

        char[] chars = s.toCharArray();
        int i = 0, j = s.length()-1 ;
        while(i<=j){
            char x = chars[i];
            char y = chars[j];
            x = convertToLower(x);
            y = convertToLower(y);
            if(!ifLower(x)){
                i++;
                continue;
            }
            if(!ifLower(y)){
                j--;
                continue;
            }
            if(x==y){
                i++;
                j--;
                continue;
            }else
            {
                return false;
            }
        }

        return true;
    }

    private boolean ifLower(char x) {
        return (48<=x && x<=57) || (97 <= x && x <= 122);
    }


    private char convertToLower(char x) {
        if ( 65 <= x && x <= 90){
            x = (char)((int)x + 32);
        }
        return x;
    }

猜你喜欢

转载自blog.csdn.net/qq_27817327/article/details/83651873