Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
#include
#include
#include
using namespace std;
/*
1. 空白没有考虑,加入trim
2. trim写错,应该是return s.substr(start, end + 1);
3. " 1 " => " 1", s.substr(start, end + 1 - start);
4. 生气了,多个空白还要压缩成一个。。。
5. 竟然是64ms..
*/
class Solution {
public :
void reverseWords( string & s) {
s = trim( s);
if ( s.length() == 0) {
return ;
}
reverseCore( s, 0, s.length());
int start = 0;
for ( int i = 0; i < s.length(); i++) {
if ( s[i] == ' ') {
reverseCore( s, start, i);
start = i + 1;
}
}
if ( s[ s.length() - 1] != ' ') {
reverseCore( s, start, s.length());
}
s = compress( s);
}
private :
void reverseCore( string & s, int start, int end) {
for ( int i = start, j = end - 1; i < j; i++, j--) {
swap( s[i], s[j]);
}
}
string trim( string & s) {
int start = 0;
while (start < s.length()) {
if ( s[start] != ' ') {
break;
}
start++;
}
int end = s.length() - 1;
while (end >= 0) {
if ( s[end] != ' ') {
break;
}
end--;
}
return s.substr(start, end + 1 - start);
}
string compress( string & s) {
string result = "" ;
for ( int i = 0; i < s.length(); i++) {
if ( s[i] != ' ') {
result += s[i];
}
else {
result += ' ';
while ( s[i] == ' ') {
i++;
}
i--;
}
}
return result;
}
};
int main() {
Solution so;
string str = "a b " ;
so.reverseWords(str);
cout << "[" << str << "]" << endl;
return 0;
}
#include
#include
#include
#include
#include
using namespace std; /* 只有16ms啊 */ class Solution { public : void reverseWords( string & s) { vector< string> words; istringstream iss(s ); string word; while (iss >> word) { words.push_back(word); } s = "" ; for ( int i = words.size() - 1; i > 0; i--) { s += words[i] + " " ; } if (words.size() > 0) { s += words[0]; } } }; int main() { Solution so; string str = " "; so.reverseWords(str); cout << "[" << str << "]" << endl; return 0; }