Drill

ProblemsC++ › warmup

Palindrome check

easywarmupStringsTwo pointersC++

A puzzle feature checks whether a phrase reads the same backwards.

isPalindrome(text: string) → bool

C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

bool isPalindrome(std::string text) {
    
}

Worked examples

CallResult
isPalindrome(std::string(""))true
isPalindrome(std::string("racecar"))true
isPalindrome(std::string("A man, a plan, a canal: Panama"))true
isPalindrome(std::string("hello"))false

Hint

Walk one index from each end, skipping anything that is not alphanumeric.

Reference solution in C++
bool isPalindrome(std::string text) {
    string s;
    for (char c : text) {
        if (isalnum(static_cast<unsigned char>(c))) s += tolower(static_cast<unsigned char>(c));
    }
    for (int i = 0, j = (int) s.size() - 1; i < j; i++, j--) {
        if (s[i] != s[j]) return false;
    }
    return true;
}

The same problem in another language

More warmup problems in C++