125. 验证回文串

Introduction

Question: 125. 验证回文串

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

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

示例 1:

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

示例 2:

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

解法一

Analysis

感觉被我写复杂了,但其实没啥难度。

Implement

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
inline char Lower(char c) {
return (c <= 'z' && c >= 'a') ? c : c + 'a' - 'A';
}
inline bool check(string &s, int i) {
return (s[i] <= '9' && s[i] >= '0') || (s[i] <= 'z' && s[i] >= 'a')
|| (s[i] <= 'Z' && s[i] >= 'A');
}
inline int nextLeft(string &s, int i, int end) {
while(i < end && !check(s, i)) {
i++;
}
return i;
}
inline int nextRight(string &s, int i, int end) {
while(i > end && !check(s, i)) {
i--;
}
return i;
}
bool isPalindrome(string s) {
int n = s.size();
int last = nextRight(s, n-1, 0);
int first = nextLeft(s, 0, last);

while(first < last && Lower(s[first]) == Lower(s[last])) {
last = nextRight(s, last - 1, first);
if (first < last)
first = nextLeft(s, first + 1, last);
}
return first == last;
}