题目链接
string reverse(string s1)
{
string s2;
string::reverse_iterator rit = s1.rbegin();
while (rit != s1.rend())
{
s2 += *rit;
rit++;
}
return s2;
}
class Solution {
public:
string reverseWords(string s) {
string s1;
int i = 0;
int j = 0;
int length = s.length();
for (i = 0; i < length; )//因为不知道具体单词长度,这里不做++处理
{
while (s[j] != ' ')//找到下一个空格
{
j++;
if (j >= length)
{
break;
}
}
int k = j - i;//所需反转的单词长度
string tmp = s.substr(i, k);
tmp = reverse(tmp);
s1 += tmp;
int m = s.find(' ');
s1 += ' ';
i += k+1;
j = i+1;
}
//最后得出的s1末尾会多一个空格,把它截断
s1 = s1.substr(0, s1.length() - 1);
return s1;
}
};