forked from Astha369/CPP_Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPalindrome.cpp
52 lines (43 loc) · 1.32 KB
/
Palindrome.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// This program utilizes stack data structure to check if a given string is pallindrome.
#include <iostream>
#include <stack>
#include <string>
#include <cctype>
// Function to remove spaces and convert a string to lowercase
std::string preprocessString(const std::string& str) {
std::string result;
for (char c : str) {
if (!std::isspace(c)) {
result += std::tolower(c);
}
}
return result;
}
// Function to check if a string is a palindrome
bool isPalindrome(const std::string& str) {
std::stack<char> charStack;
std::string processedStr = preprocessString(str);
// Push characters onto the stack
for (char c : processedStr) {
charStack.push(c);
}
// Pop characters from the stack and compare with the string
for (char c : processedStr) {
if (charStack.top() != c) {
return false; // Characters do not match, not a palindrome
}
charStack.pop();
}
return true; // All characters matched, it's a palindrome
}
int main() {
std::string input;
std::cout << "Enter a string: ";
std::getline(std::cin, input);
if (isPalindrome(input)) {
std::cout << "The string is a palindrome." << std::endl;
} else {
std::cout << "The string is not a palindrome." << std::endl;
}
return 0;
}