Skip to content

Commit 37819d6

Browse files
committed
Added Palindrome Algorithm in Cpp and updated README.md
1 parent 8b245e8 commit 37819d6

File tree

2 files changed

+58
-2
lines changed

2 files changed

+58
-2
lines changed

README.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -3500,8 +3500,8 @@ Com o objetivo de alcançar uma abrangência maior e encorajar mais pessoas a co
35003500
</a>
35013501
</td>
35023502
<td> <!-- C++ -->
3503-
<a href="./CONTRIBUTING.md">
3504-
<img align="center" height="25" src="https://cdn.jsdelivr.net/gh/devicons/devicon/icons/github/github-original.svg" />
3503+
<a href="/src/cpp/Palindrome.cpp">
3504+
<img align="center" height="25" src="https://cdn.jsdelivr.net/gh/devicons/devicon/icons/cplusplus/cplusplus-original.svg" />
35053505
</a>
35063506
</td>
35073507
<td> <!-- Java -->

src/cpp/Palindrome.cpp

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/*
2+
isPalindrome Algorithm in C++
3+
Ricardo Ferreira Carvalheira - 2023
4+
https://github.com/ricardocarva
5+
6+
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
7+
8+
Given a string s, return true if it is a palindrome, or false otherwise.
9+
*/
10+
#include <iostream>
11+
12+
#include <string>
13+
14+
using namespace std;
15+
16+
bool isPalindrome(string s) {
17+
// Step 1: Convert all characters to lowercase
18+
for (char& c : s) {
19+
c = std::tolower(c);
20+
}
21+
22+
// Step 2: Remove non-alphanumeric characters
23+
std::string alphanumericStr;
24+
for (char c : s) {
25+
if (std::isalnum(c)) {
26+
alphanumericStr.push_back(c);
27+
}
28+
}
29+
30+
// Step 3: Check if the resulting string is a palindrome
31+
int left = 0;
32+
int right = alphanumericStr.length() - 1;
33+
34+
while (left < right) {
35+
if (alphanumericStr[left] != alphanumericStr[right]) {
36+
return false;
37+
}
38+
left++;
39+
right--;
40+
}
41+
return true;
42+
}
43+
44+
int main() {
45+
std::string input;
46+
std::cout << "Enter a string: ";
47+
std::cin >> input;
48+
49+
if (isPalindrome(input)) {
50+
std::cout << "The string is a palindrome." << std::endl;
51+
}
52+
else {
53+
std::cout << "The string is not a palindrome." << std::endl;
54+
}
55+
return 0;
56+
}

0 commit comments

Comments
 (0)