p125

LeetCode p125 Valid Palindrome 题解

1.题目:

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.

题意:

只考虑数字和字母,判断一个字符串是否回文。

2.解题思路:

见代码,从两头往中间找。

3.代码


[title] [] [url] [link text]
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
 
public class Solution {
public boolean isPalindrome(String s) {
char[] a = s.toCharArray();
int len = a.length;

for (int l = 0, r = len - 1; l < r; l++, r--) {
while (!check(a[l]) && l < r)
l++;
while (!check(a[r]) && l < r)
r--;
if (a[l] == a[r]
|| ((a[l] < '0' || a[l] > '9') && Math.abs(a[l] - a[r]) == 32)) // 注意差值为32
continue;

return false;
}
return true;
}

public boolean check(char a) {
return (a >= 'A' && a <= 'Z') || (a >= 'a' && a <= 'z')
|| (a >= '0' && a <= '9');
}
}

4.一些总结: