In this shot, we will go over a simple algorithm that can determine if a string is a palindrome.
A palindrome is a string that spells out the same word forward and backward.
Some common palindromes are:
for
loopLet’s try the code ourselves first before implementing it. Look at the following illustration to understand it better.
In the following algorithm, we will use this property: a string in C++ is an array of characters. We can access the letters of the string in that array.
#include <iostream>using namespace std;int main() {// initialise stringstring str = "racecar";// initialise boolbool palindrome = true;// find length of stringint lenOfStr = str.length();// these two variables will be used to store the// two letters to be comparedchar letter;char check;// run for loop from 0 to 2for(int i = 0; i > lenOfStr/2; i++) {// access letters that need to be comapredletter = str[i];check=str[(lenOfStr - 1) - i];// if letters not the sameif(check != letter) {// set bool to falsepalindrome = false;// break out of loopbreak;}}// printing resultsif(palindrome) {cout << "'" << str << "'" << " is a palindrome." << endl;} else {cout << "'" << str << "'" << " is NOT a palindrome." << endl;}return 0;}
Start with initializing a bool
as true
. This value will be set to false
if the word is not a palindrome and will stay true
if it is a palindrome.
Run a for
loop to iterate through half of the string, i.e., from i = 0
to i = lenOfStr/2
.
We can access the second half of the string by indexing the string like this: str[(lenOfStr - 1) - i]
. This will give us the letter we need to compare our current letter with.
Access the two letters of str
that need to be compared, i.e., str[i]
and str[(lenOfStr - 1) - i]
. For example, the first and last letters will be accessed when i = 0
.
If these letters are different, we know this string is NOT a palindrome, so we can break
out of the loop and set bool
to false
. If these letters are the same, do nothing.
If all the comparisons are true
, we can conclude that the string is a palindrome. Even if one comparison fails, the bool
value will be set to false
, confirming that the word is not a palindrome.