-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathPalindrome2.cpp
102 lines (66 loc) · 1.21 KB
/
Palindrome2.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include<iostream>
#include<stack>
using namespace std;
//Method-1 :Iterative method
void Palindrome(string s) {
int start = 0 ;
int end = (s.length() - 1);
while(start <= end)
{
if(s[start]==s[end])
{
start++;
end--;
}
//if the left and right values don't match , simply break out of while loop and test for base condition
else {
break;
}
}
if(start < end) {
cout<<"Not a palindrome"<<endl;
}
else
{
cout<<"Palindrome string"<<endl;
}
}
//T(n) = O(n)
//Method-2 :using stack
void PalindromeStack(string s,stack <char>&p)
{
//pushing contents of string to stack
for(int i=0 ; i < s.length() ; i++) //O(n)
{
p.push(s[i]); //O(1)
}
//comparing the expression and top of stack
// for(int i = 0 ; i < s.length() ; i++)
// {
// if(s[i] == p.top())
// {
//
// p.pop();
//
// }
// }
int i=0;
while( i < s.length() && s[i]==p.top()) //O(n)
{
p.pop(); //O(1)
i++;
}
if(p.empty()) {
cout<<"Palindrome string."<<endl;
}
else {
cout<<"Not a palindrome string."<<endl;
}
} //Time complexity = O(n) -linear time
int main() {
stack<char>c;
string s;
getline(cin,s);
PalindromeStack(s,c);
return 0;
}