leetcode-125-Valid-Palindrome

描述


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:

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

Example 2:

1
2
Input: "race a car"
Output: false

分析


判断一个字符串是否为回文,有意思的是,题目里明明说了都是字母,用 Java 实现的代码里,判断时却不能用 isLetter,用 isLetterOrDigit 才能通过。

解决方案1(Java)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public boolean isPalindrome(String s) {
if (s == null) {
return false;
}

int l = 0, r = s.length() - 1;
while (l <= r) {
while(l < r && !Character.isLetterOrDigit(s.charAt(l))) {
l++;
}
while(l < r && !Character.isLetterOrDigit(s.charAt(r))) {
r--;
}
if (Character.toLowerCase(s.charAt(l)) == Character.toLowerCase(s.charAt(r))) {
l++;
r--;
} else {
return false;
}
}
return true;
}
}

相关问题


题目来源