-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathreverseStringUsingStack.cpp
67 lines (48 loc) · 1.13 KB
/
reverseStringUsingStack.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
#include<iostream>
#include<string>
#include<stack>
using namespace std;
//------------------------USING STACK-------------------- takes Time coplexity=O(n),space complexity=O(n) due to space allocated for stack
//void reverse(string str) {
// stack<char> s;
//
// //push string to stack
// //reading the string char one by one and pusing it to stack
// for(int i=0;i<str.length();i++) {
// s.push(str[i]);
// }
//
// //popping the chars and revrrsing
// for(int i=0; i<str.length();i++) {
// str[i] = s.top(); //storing top element of stack in str,reversal
// s.pop(); //popping
// }
// cout<<str; //string is now updated and reversed
//}
//int main() {
// string name;
// getline(cin,name);
// reverse(name);
//
// return 0;
//}
//TIME COMPLEXITY=o(n) AND SPACE COMPLEXITY= O(1) , n = size of string for the below method
void reverse(string str) {
int i = 0;
int j = str.length()-1;
// if(i==j) {
// return;
// }
while(i<j) {
swap(str[i],str[j]); //swapping
i++;
j--;
}
cout<<str; //now str is updated with new reversed value
}
int main() {
string name;
getline(cin,name);
reverse(name);
return 0;
}