[LintCode] 有效回文串

 1 class Solution {
 2 public:
 3     /**
 4      * @param s A string
 5      * @return Whether the string is a valid palindrome
 6      */
 7     bool isPalindrome(string& s) {
 8         // Write your code here
 9         int left = 0, right = s.length() - 1;
10         while (left < right) {
11             while (left < right && !isdigit(s[left]) && !isLetter(s[left]))
12                 left++;
13             if (left == right) break;
14             while (right > left && !isdigit(s[right]) && !isLetter(s[right]))
15                 right--;
16             if (right == left) break;
17             if (!match(s[left++], s[right--])) return false;
18         }
19         return true;
20     }
21 private:
22     bool isLetter(char s) {
23         return (s >= 'A' && s <= 'Z') || (s >= 'a' && s <= 'z');
24     }
25     bool match(char s, char t) {
26         if (isLetter(s) && isLetter(t))
27             return (s == t) || (s - t == 32) || (t - s == 32);
28         return s == t;
29     }
30 };

 

posted @ 2015-06-28 15:48  jianchao-li  阅读(229)  评论(0编辑  收藏  举报