Skip to content

algo(cpp-palindrome): adding implementation #43

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
#include <iostream>
#include <string>
#include <math.h> /* floor */

/*
* Palindrome checker
*
* Write code to check if a string is palindrome or not?
*
* A string is a palindrome if the string is the same
* whether spelled forwards or backwards
*/

std::string isPalindrome(std::string text) {
// remove non alphabetic characters
std::string newText;
for (int i = 0; i < text.size(); i++) {
if (std::isalpha(text[i])) {
newText += std::tolower(text[i]);
}
}

// check if a string is a palindrome.
// Only check half of the array instead of the whole string
for (int i = 0; i < floor(newText.size() / 2) + 1; i++) {
if (newText[i] != newText[newText.size() - i - 1]) {
return "False";
}
}
return "True";
}

void test(std::string text) {
std::cout << text << ": " << isPalindrome(text) << std::endl;
}

int main(int argc, char *argv[]) {
std::cout << "palindrome tests" << std::endl;
test("racecar");
test("r a c e c a r!");
test("Mother Eve's noose we soon sever, eh Tom?");
test("On a clover, if alive, erupts a vast, pure evil; a fire volcano.");

std::cout << "Non-palindrome tests" << std::endl;
test("abcd");
test("palindrome");
test("!!hacktoberfest!!");
return 0;
}