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
Problem: 151. Reverse Words in a String
Problem Link:
Companies Asked: Visa, Apple, Amazon, Google, LinkedIn, Microsoft, Facebook, PayTM, Salesforce
Approach:
Split the whole sentence word by word.
Pushed them into a vector of string type.
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;
}
};