DEV Community

Adam La Rosa
Adam La Rosa

Posted on

Palindrome Elegance

Playing with a little C++ I eventually came across the problem of checking to see if a string of characters is a palindrome or not. Using a solution I've had success with I gave this to the compiler...

#include <iostream>
using namespace std;

int main() {
    string word = "";
    string test = "";

    cout << "Enter something: ";
    cin >> word;

    for (int i = word.length() - 1; i >= 0; i--) {
        test = test + word[i];
    }

    word == test ? cout << "Palendrome!\n" : cout << "Not.\n";

}

Like before, this did the job. I was curious though. There must be a better way to solve this problem. A quick search around provided me this gem.

bool is_palindrome(string text) {
    int start = 0;
    int end = text.length() - 1;

    while (end > start) { 
        if (text[start++] != text[end--]) {
        return false;
        }
    }
    return true;
}

Right off the bat I'm liking this solution more. Where taking a word and creating a reverse of it seems like the right approach, this second solution proves it to be too labor intensive. Our while loop iterates over what should be two equal characters and compares them. As soon as two don't match, not a palindrome.

Top comments (2)

Collapse
 
aryaziai profile image
aryaziai

Efficient solution!

Collapse
 
adamlarosa profile image
Adam La Rosa

I especially dig how the "start" & and "end" variables are incremented, not as a stand alone instruction, but in the IF statement's logic.