leetcode125 Valid Palindrome-zh
# 125. 验证回文串 (opens new window)
English Version (opens new window)
# 题目描述
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: "A man, a plan, a canal: Panama" 输出: true
示例 2:
输入: "race a car" 输出: false
# 解法
# Python3
class Solution:
def isPalindrome(self, s: str) -> bool:
i, j = 0, len(s) - 1
while i < j:
if not s[i].isalnum():
i += 1
elif not s[j].isalnum():
j -= 1
elif s[i].lower() != s[j].lower():
return False
else:
i += 1
j -= 1
return True
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# Java
class Solution {
public boolean isPalindrome(String s) {
int i = 0, j = s.length() - 1;
while (i < j) {
if (!Character.isLetterOrDigit(s.charAt(i))) {
++i;
} else if (!Character.isLetterOrDigit(s.charAt(j))) {
--j;
} else if (Character.toUpperCase(s.charAt(i)) != Character.toUpperCase(s.charAt(j))) {
return false;
} else {
++i;
--j;
}
}
return true;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# C++
class Solution {
public:
bool isPalindrome(string s) {
int i = 0, j = s.size() - 1;
while (i < j) {
if (!isAlphaNum(s[i])) ++i;
else if (!isAlphaNum(s[j])) --j;
else if ((s[i] + 32 - 'a') % 32 != (s[j] + 32 - 'a') % 32) return false;
else {
++i;
--j;
}
}
return true;
}
private:
bool isAlphaNum(char &ch) {
if (ch >= 'a' && ch <= 'z') return true;
if (ch >= 'A' && ch <= 'Z') return true;
if (ch >= '0' && ch <= '9') return true;
return false;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# tTypeScript
function isPalindrome(s: string): boolean {
let left: number = 0, right: number = s.length - 1;
while (left < right) {
let char1: string = s.charAt(left);
let char2: string = s.charAt(right);
if (!(/[a-zA-Z0-9]/).test(char1)) {
++left;
} else if (!(/[a-zA-Z0-9]/).test(char2)) {
--right;
} else if (char1.toLocaleLowerCase() != char2.toLocaleLowerCase()) {
return false;
} else {
++left;
--right;
}
}
return true;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# ...
1
编辑 (opens new window)
上次更新: 2021/10/30, 12:58:38