hi, let Avik connect you.


** You can give your thought about this content and request modifications if needed from Ask For Modifications page. Thank You.

** You can check all the posts on the Posts page.

** More about me in the About Me section.

Reverse Words in a String


  • Approach:

    1. Split the whole sentence word by word.

    2. Pushed them into a vector of string type.

    3. Concatenate each word of the vector from the ending position to starting.


  • Time and Space Complexity:

      • Time Complexity: O(N)

      • Space Complexity: O(N)


Code [C++]

class Solution {

public:

string reverseWords(string str) {

stringstream ss(str);

vector<string>ans;

while(ss >> str) ans.push_back(str);

int n = ans.size();

str = "";

for(int i=n-1; i>=0; i--){

str += ans[i];

if(i>0) str +=" ";

}

return str;

}

};