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) {
string tmps;
int tmpi = 0, endi = s.size(), first = 0;
for( ; first < s.size(); ++first )
if( s[ first ] != ' ' )
break;
for( int i = s.size()-1; i >= first; --i )
{
if( s[ i ] == ' ' )
{
if( s[ i+1 ] != '\0' && s[ i+1 ] != ' ' )
{
for( int j = i+1; j < endi; ++j )
tmps.push_back( s[ j ] );
tmps.push_back( ' ' );
}
endi = i;
}
else if( i == first )
for( int j = i; j < endi; ++j )
tmps.push_back( s[ j ] );
}
s = tmps;
}
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)