Leetcode-valid-palindrome

题目描述

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.


这一题用循环的方法比较好解决,我们先把所有的字母变成小写(也可以变成大写),这是为了更好的判断是不是字母。当字符串中不是字母或数字时就跳过。两个下标low和high从字符串两边开始逼近,如果不一致就肯定不是回文,当low>=high时都一致,则是回文

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
public class Solution {

public boolean isPalindrome(String s) {

if (s == null || s.length() == 0) {

return true;

​ }

​ String str = s.toLowerCase();

int low = 0;

int high = s.length() - 1;

while (low < str.length() && !isEnglishOrNum(str.charAt(low))) {

​ low++;

​ }

while (high > 0 && !isEnglishOrNum(str.charAt(high))) {

​ high--;

​ }

while (low < high) {

if (str.charAt(low) != str.charAt(high)) {

return false;

​ }

​ low++;

​ high--;

while (!isEnglishOrNum(str.charAt(low))) {

​ low++;

​ }

while (!isEnglishOrNum(str.charAt(high))) {

​ high--;

​ }

​ }

return true;

​ }

private boolean isEnglishOrNum(char c) {

if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) {

return true;

​ }

return false;

​ }

}