LeetCode Problem (Reverse Words in a String)

Link to the Problem

Here we used the Stack Approach to tackle the problem :

The first thing that comes to our mind is to reverse each word independently and combine it in the string and that is what we will do here.

  1. To do this stack will be the perfect data structure as it follows the LIFO principle so it will be easy for us to reverse the words now let's dive into the code step by step

     class Solution {
     public:
         string reverseWords(string s) {
             stack<char> st; // stack ds of char type 
             string result = ""; // this is the string where we will store our final ans
             for (char c : s) { // this loop will run to end of the string s(which is given to us)
                 if (c != ' ') { // if c is not equal to a space then push char c in stack st
                     st.push(c);
                 } else { // else  
                     while (!st.empty()) { // if stack is not empty 
                         result += st.top(); // result will store the top value of the stack it will help us in rversing ht string
                         st.pop(); // when the character is added in the result we will pop the element out of the stack
                     }
                     result += ' '; // when a reversed word will be in our stack we will add a space in the sentence 
                 }
             }
             while (!st.empty()) {
                 result += st.top();
                 st.pop();
             }
             return result;
         }
     };