summaryrefslogtreecommitdiff
path: root/top-interview-questions/easy/strings/05_valid_palindrome.cc
blob: 1b4ca6f2dbb2f9f9130dc1cb7eed705768b60c6b (plain)
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
class Solution {
public:
    bool IsAlphaNum(char c) {
        return
            (('a' <= c) && (c <= 'z')) ||
            (('A' <= c) && (c <= 'Z')) ||
            (('0' <= c) && (c <= '9'));
    }

    void Transform(string& s) {
        size_t j = 0;
        for (size_t i = 0; i < s.size(); ++i) {
            if (IsAlphaNum(s[i])) {
                s[j] = std::tolower(s[i]);
                j++;
            }
        }
        s.resize(j);
    }

    bool isPalindrome(string s) {
        Transform(s);
        for (size_t i = 0; i < s.size()/2; ++i) {
            if (s[i] != s[s.size()-i-1]) {
                return false;
            }
        }
        return true;
    }
};