LeetCode125 Valid Palindrome

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. (Easy)

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.

 

分析:

回文判断思路比较直观就是两根指针一前一后比较即可。但本题中只判断字母和数字,其他字符直接忽略,所以要加一些处理。

 

代码:

 1 class Solution {
 2 public:
 3     bool isPalindrome(string s) {
 4         if (s.size() == 0) {
 5             return true;
 6         }
 7         for (int i = 0; i < s.size(); ++i) {
 8             if (s[i] >= 'A' && s[i] <= 'Z') {
 9                 s[i] += ('a' - 'A');
10             }
11         }
12         int i = 0, j = s.size() - 1;
13         while (i <= j) {
14             if ( !( (s[i] >= 'a' && s[i] <= 'z') || (s[i] >= '0' && s[i] <= '9')) ) {
15                 i++;
16                 continue;
17             }
18             if (!( (s[j] >= 'a' && s[j] <= 'z') || (s[j] >= '0' && s[j] <= '9') )) {
19                 j--;
20                 continue;
21             }
22             if (s[i] != s[j] ) {
23                 return false;
24             }
25             i++;
26             j--;
27         }
28         return true;
29     }
30 };

 

posted @ 2016-12-06 22:06  wangxiaobao1114  阅读(182)  评论(0编辑  收藏  举报