欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 125: Valid Palindrome

程序员文章站 2024-03-06 21:56:14
...

问题描述

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

实现

class Solution {
    public boolean isPalindrome(String s) {
        String ss = s.replaceAll("[^0-9a-zA-Z]", "").toLowerCase();
        if (s.length() == 0 || ss.length()<=1 )
            return true;
        int ps = 0;
        int pe = ss.length() - 1;
        boolean result = true;
        while (ps <= pe) {
            if (ss.charAt(ps++) != ss.charAt(pe--)) {
                result = false;
                break;
            }
        }
        return result;
    }
}