125. Valid Palindrome

Total Accepted: 91860
Total Submissions: 392114
Difficulty: Easy

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.

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
25
26
27
public class Solution {
public boolean isPalindrome(String s) {
if ("".equals(s))
return true;
for (int i = 0, j = s.length() - 1; i < j; ++i, --j) {
char ci = s.charAt(i);
while (i < j
&& !(ci >= 'a' && ci <= 'z' || ci >= 'A' && ci <= 'Z' || ci >= '0' && ci <= '9'))
ci = s.charAt(++i);

char cj = s.charAt(j);
while (i < j
&& !(cj >= 'a' && cj <= 'z' || cj >= 'A' && cj <= 'Z' || cj >= '0' && cj <= '9'))
cj = s.charAt(--j);

if (i < j) {
if (ci >= 'A' && ci <= 'Z')
ci += 32;
if (cj >= 'A' && cj <= 'Z')
cj += 32;
if (ci != cj)
return false;
}
}
return true;
}
}

打个小广告

欢迎加入我的小专栏「基你太美」一起学习。