125. Valid Palindrome
2026/1/12大约 1 分钟约 311 字
125. Valid Palindrome
难度: Easy
题目描述
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s, return true if it is a palindrome, or false otherwise.
Example 1:
Input: s = "A man, a plan, a canal: Panama" Output: true Explanation: "amanaplanacanalpanama" is a palindrome.
Example 2:
Input: s = "race a car" Output: false Explanation: "raceacar" is not a palindrome.
Example 3:
Input: s = " " Output: true Explanation: s is an empty string "" after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome.
Constraints:
1 <= s.length <= 2 * 105sconsists only of printable ASCII characters.
解题思路
代码实现
解决方案
java
class Solution {
public boolean isPalindrome(String s) {
int n = s.length();
for (int i = 0, j = n - 1; i < j;) {
char cI = Character.toLowerCase(s.charAt(i));
char cJ = Character.toLowerCase(s.charAt(j));
if (!isValid(cI)) {
i++;
continue;
}
if (!isValid(cJ)) {
j--;
continue;
}
if (cI != cJ) {
return false;
}
i++;
j--;
}
return true;
}
private boolean isValid(char cI) {
if ((cI >= '0' && cI <= '9') || (cI >= 'a' && cI <= 'z')) {
return true;
}
return false;
}
}