Commit 1fcfab1e authored by Sadman Kazi's avatar Sadman Kazi 🎸

Solve reverse words in a string

parent b6a99de1
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
class Solution {
public:
void reverseWords(string &s) {
std::vector<std::string> words;
std::string buffer;
for (int i = s.length()-1; i >= 0; i--) {
buffer = "";
while (s[i] != ' ') {
buffer = s[i] + buffer;
i--;
if (i < 0) break;
}
if (buffer.length() > 0) {
words.push_back(buffer);
}
}
s = "";
for (auto iter = words.begin(); iter != words.end(); iter++) {
s += *iter + " ";
}
s = s.substr(0, s.length()-1);
std::cout << s << std::endl;
}
};
int main () {
Solution s;
std::string str = "the sky is blue";
s.reverseWords(str);
str = " the sky is blue ";
s.reverseWords(str);
str = "a";
s.reverseWords(str);
return 0;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment