From : https://leetcode.com/problems/reverse-words-in-a-string/
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
class Solution {
public:
void reverseWords(string &s) {
stack<string> stc;
string tstr="";
s += ' ';
int len = s.length();
for(int i=0; i<len; i++) {
if(i==0 && s[i]==' ') continue;
if(s[i]==' ' && s[i-1]==' ') continue;
if(s[i]==' ' && tstr!="") {
stc.push(tstr);
tstr = "";
} else {
tstr += s[i];
}
}
s="";
while(!stc.empty()) {
s += stc.top();
stc.pop();
if(stc.empty()) {
break;
}
s += " ";
}
}
};
Solution 2:
class Solution {
public:
void reverseWords(string &s) {
string ts;
int end = s.size()-1, start = end;
while(end>=0) {
while(end>=0 && s[end]==' ') end--;
start = end;
while(start>=0 && s[start]!=' ') start--;
if(start!=0 && start<end && ts!="") ts.append(" ");
if(start < end) ts.append(s.substr(start+1, end-start));
end = start;
}
s = ts;
}
};