leetcode 125

验证回文串

Posted by Static on June 19, 2020

题目链接:https://leetcode-cn.com/problems/valid-palindrome/

题目描述


分析

1. 循环

左指针和右指针对比


代码实现

public enum Q125 {
    instance;

    public boolean isPalindrome(String s) {
        if(s==null||s.length()==0)return true;
        for(int i=0,j=s.length()-1;i<j;){
            char left=s.charAt(i);
            if(!isValidChar(left)){
                i++;
                continue;
            }
            char right=s.charAt(j);
            if(!isValidChar(right)){
                j--;
                continue;
            }

            if(lower(left)!=lower(right)){
                return false;
            }
            i++;
            j--;
        }
        return true;
    }

    // 48-57:'0'-'9'
    // 97-122:'a'-'z'
    // 65-90:'A'-'Z'
    private boolean isValidChar(char c){
        return (c>='a'&&c<='z')||
                (c>='A'&&c<='Z')||
                (c>='0'&&c<='9');
    }

    private char lower(char c){
        if(c>='A'&&c<='Z'){
            return (char)(c+32);
        }
        return c;
    }

    public static void main(String[] args) {
        // assert true
        System.out.println(Q125.instance.isPalindrome("A man, a plan, a canal: Panama"));
        // assert true
        System.out.println(Q125.instance.isPalindrome("race a car"));
        // assert false
        System.out.println(Q125.instance.isPalindrome("9;8'4P?X:1Q8`dOfJuJXD6FF,8;`Y4! YBy'Wb:ll;;`;\"JI0c2uvD':!LAk:s\"!'0.!2B55.T1VI?00Du?1,l``RFsc?Y?9vD5 K'3'1b!N8hn:'l. R:9:o`m1r.M2mrJ?`Wjv1`G6i6G`1vjW`?Jrm2M.r1m`o:::R .l':nh8N!b1'3'K 5Dv9?Y?csFR``l,1?uD00?IV1T.55B2!.0'!\"s:kAL!:'Dvu2c0IJ\";`;;ll9bW'yBY !4Y`;8,FF6DXJuJfOd`8Q1:X?P4'8;9"));
        // assert true
        System.out.println(Q125.instance.isPalindrome("Zeus was deified, saw Suez."));
    }
}