1. 程式人生 > >LeetCode之驗證迴文串

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