导航
导航
文章目录
  1. 题目
  2. 翻译

LeetCode-125.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.

翻译

给出一个字符串,判断它是否是回文的,只考虑字母数字的字符,并忽略大小写。
例如,
“A man, a plan, a canal: Panama” 是一个回文。
“race a car” 不是回文。
注意:
你是否考虑到字符串可能为空?这是一个面试时的好问题。
对于本题,认为空字符串是一个合法的回文字符串。

设立左右两个指针,分别从头尾遍历,左右字符不同时返回false,相遇时返回true。本题需要特别注意的是1、非字母数字字符,2、大小写:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Solution {
public boolean isPalindrome(String s) {
int left = 0, right = s.length() - 1;
while (left < right) {
while (!isValid(s.charAt(left))) {
left++;
if (left == right) return true;
}
while (!isValid(s.charAt(right))) {
right--;
if (left == right) return true;
}
if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right)))
return false;
left++;
right--;
}
return true;
}

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