[LeetCode] Valid Palindrome

The suggested solution to this problem has given a clear idea. The tricky part of this problem is to handle all the edge cases carefully and write a clean code.

The following code should be self-explanatory. Note that the use of toupper avoid some messy if-else statements.

 1 class Solution {
 2 public:
 3     bool isPalindrome(string s) {
 4         int l = 0, r = s.length() - 1;
 5         while (l < r) {
 6             while (l < r && !isalnum(s[l])) l++;
 7             if (l >= r) break;
 8             while (r > l && !isalnum(s[r])) r--;
 9             if (toupper(s[l++]) != toupper(s[r--]))
10                 return false;
11         }
12         return true;
13     }
14 };

 

posted @ 2015-07-10 20:40  jianchao-li  阅读(159)  评论(0编辑  收藏  举报