LeetCode125-验证回文串

题目链接

英文链接:https://leetcode.com/problems/valid-palindrome/

中文链接:https://leetcode-cn.com/problems/valid-palindrome/

题目详述

给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。

说明:本题中,我们将空字符串定义为有效的回文串。

示例 1:

1
2
输入: "A man, a plan, a canal: Panama"
输出: true

示例 2:

1
2
输入: "race a car"
输出: false

题目详解

验证是否是回文串,不过只考虑字母和数字字符,忽略字母的大小写。运用双指针从两侧往中间扫描即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class LeetCode_00125 {

public boolean isPalindrome(String s) {
int i = 0;
int j = s.length() - 1;
while (i < j) {
while (i < j && !Character.isLetterOrDigit(s.charAt(i))) {
++i;
}
while (i < j && !Character.isLetterOrDigit(s.charAt(j))) {
--j;
}
if (Character.toLowerCase(s.charAt(i++)) != Character.toLowerCase(s.charAt(j--))) {
return false;
}
}
return true;
}
}