LeetCode 125 验证回文串

问题

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Note: For the purpose of this problem, we define empty string as valid palindrome.

Example 1:

Input: "A man, a plan, a canal: Panama"
Output: true

Example 2:

Input: "race a car"
Output: false


分析

1 很容易想到char[] 数组化,然后用while循环遍历,i,j满足的条件 i

2 while循环里的逻辑分3步 1 前置i固定字符

                                     2 后置j固定字符

                                     3 然后比较这两个位置的值是否相同,相同继续处理 i++ j++

3  用到了Character类里的方法 1 判断是否是数字和英文字符 . Character.isLetterOrDigit

                                           2 字母的小写化 Characte.toLowerCase


代码

 public boolean isPalindrome(String s) {
        char[] cha = s.toCharArray();
        int i = 0, j = cha.length - 1;
        while(i < j){
            if(!Character.isLetterOrDigit(cha[i]))
                i++;
            else if(!Character.isLetterOrDigit(cha[j]))
                j--;
            else
                if(Character.toLowerCase(cha[i]) == Character.toLowerCase(cha[j])){
                    i++;
                    j--;
                }else{
                    return false;
                }
        }
        return true;
}


你可能感兴趣的:(LeetCode)