@@ -6,21 +6,51 @@ using namespace std;
66
77// ------------------------USING STACK-------------------- takes Time coplexity=O(n),space complexity=O(n) due to space allocated for stack
88
9+ // void reverse(string str) {
10+ // stack<char> s;
11+ //
12+ // //push string to stack
13+ // //reading the string char one by one and pusing it to stack
14+ // for(int i=0;i<str.length();i++) {
15+ // s.push(str[i]);
16+ // }
17+ //
18+ // //popping the chars and revrrsing
19+ // for(int i=0; i<str.length();i++) {
20+ // str[i] = s.top(); //storing top element of stack in str,reversal
21+ // s.pop(); //popping
22+ // }
23+ // cout<<str; //string is now updated and reversed
24+ // }
25+
26+ // int main() {
27+ // string name;
28+ // getline(cin,name);
29+ // reverse(name);
30+ //
31+ // return 0;
32+ // }
33+
34+ // TIME COMPLEXITY=o(n) AND SPACE COMPLEXITY= O(1) , n = size of string for the below method
35+
936void reverse (string str) {
10- stack<char > s;
1137
12- // push string to stack
13- // reading the string char one by one and pusing it to stack
14- for (int i=0 ;i<str.length ();i++) {
15- s.push (str[i]);
16- }
38+ int i = 0 ;
39+ int j = str.length ()-1 ;
40+
41+
42+ // if(i==j) {
43+ // return;
44+ // }
1745
18- // popping the chars and revrrsing
19- for (int i=0 ; i<str.length ();i++) {
20- str[i] = s.top (); // storing top element of stack in str,reversal
21- s.pop (); // popping
46+ while (i<j) {
47+
48+ swap (str[i],str[j]); // swapping
49+ i++;
50+ j--;
2251 }
23- cout<<str; // string is now updated and reversed
52+
53+ cout<<str; // now str is updated with new reversed value
2454}
2555
2656int main () {
@@ -31,36 +61,6 @@ int main() {
3161 return 0 ;
3262}
3363
34- // TIME COMPLEXITY=o(n) AND SPACE COMPLEXITY= O(1) , n = size of string for the below method
35-
36- // void reverse(string str) {
37- //
38- // int i = 0;
39- // int j = str.length()-1;
40- //
41- //
42- // // if(i==j) {
43- // // return;
44- // // }
45- //
46- // while(i<j) {
47- //
48- // swap(str[i],str[j]); //swapping
49- // i++;
50- // j--;
51- // }
52- //
53- // cout<<str; //now str is updated with new reversed value
54- // }
55- //
56- // int main() {
57- // string name;
58- // getline(cin,name);
59- // reverse(name);
60- //
61- // return 0;
62- // }
63-
6464
6565
6666
0 commit comments