-
Notifications
You must be signed in to change notification settings - Fork 11
/
palindromeUsingStack.cpp
88 lines (67 loc) · 1.89 KB
/
palindromeUsingStack.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
# Program : To check whether the string is a palindrome or not using Stack.
# Auhtor : Vipin Kumar
# Created on : 09-03-2018 21:56 IST
*/
#include<iostream>
#include<string>
#include<stack>
#include<conio.h>
#include<math.h>
using namespace std;
bool isPalindrome(string givenString) {
/*
Objective : To check whether the string is a palindrome or not.
Input Variables : givenString - string - given string to be checked.
Description : isPalindrome function definiton.
Return Value : true/false
Approach : STL Stack is used to do the needful.
*/
int length = givenString.length();
if (length == 1) {
return true;
}
else {
stack <char> s;
int iteratorLength = length/2;
for (int i = 0; i < iteratorLength; i++) {
s.push(givenString[i]);
}
char temp;
if (length % 2 != 0) {
iteratorLength++;
}
for (int i = iteratorLength; i < length; i++) {
temp = s.top();
if (temp == givenString[i]) {
s.pop();
continue;
}
else {
return false;
}
}
return true;
}
}
int main() {
/*
Objective : To check whether the string is a palindrome or not.
Input Variables : None
Description : main function definiton.
Return Value : 0 - succesful termination of program.
Approach : Invoke isPalindrome Function.
*/
string givenString;
bool answer;
cout << "Enter a string: ";
cin >> givenString;
answer = isPalindrome(givenString);
if (answer == true) {
cout << givenString << " is Palindrome.";
}
else {
cout << givenString << " is NOT Palindrome.";
}
return 0;
}