LeetCode每日一题:有效地回文串

问题描述

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama"is a palindrome.
"race a car"is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.

问题分析

这题是让我们求回文字符串的,忽略所有的空格和标点,只保留字母和数字形成新的字符串,再判断是否是回文就行了

代码实现

public boolean isPalindrome(String s) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (Character.isDigit(s.charAt(i)) || Character.isLetter(s.charAt(i))) {
                stringBuilder.append(s.charAt(i));
            }
        }//转化成只剩下字母和数字的字符串
        String str = new String(stringBuilder.toString());
        int i = 0;
        int j = str.length() - 1;
        while (i < j) {
            if (Character.toLowerCase(str.charAt(i)) != Character.toLowerCase(str.charAt(j))) return false;
            i++;
            j--;
        }
        return true;
    }

你可能感兴趣的:(LeetCode每日一题:有效地回文串)