String problems by using C++

151. Reverse Words in a String

Jimmy (xiaoke) Shen
1 min readJul 15, 2020

My naive solution

class Solution {
public:
string reverseWords(string s_) {
if(s_.length()==0)return s_;
vector<string> s;
string this_c = "";
for(auto c:s_)
{
if (c!=' ')
{
this_c += c;
}
else
{
s.push_back(this_c);
this_c = "";
}
}
s.push_back(this_c);
reverse(s.begin(),s.end());
string ret = "";
for (auto word:s)
{
if (word=="")continue;
ret += word;
ret += " ";
}
if(ret.length()>0)ret.pop_back();
return ret;
}
};

A better solution from HERE by using Stringstream

class Solution {
public:
string reverseWords(string s) {
stringstream in(s);
string word;
string ret = "";
while (in >> word) {
reverse(word.begin(), word.end());
ret += word + " ";
}
if (!ret.empty()) {
ret.pop_back();
reverse(ret.begin(), ret.end());
}
return ret;
}
};

--

--