LeetCode 125 Verification Palindromes

question

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


analyze

1 It is easy to think of char[] array, and then use while loop to traverse, i, j satisfy the condition i<j.

2 The logic in the while loop is divided into 3 steps 1 Prefix i fixed character

                                     2 followed by j fixed character

                                     3 Then compare whether the values ​​of these two positions are the same, and continue to process i++ j++

3 The method 1 in the Character class is used to determine whether it is a number or an English character. Character.isLetterOrDigit

                                           2 letter lowercase Character.toLowerCase


code

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


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324821701&siteId=291194637