!!!题目链接!!!
Solution:
class Solution {
public:
string reverseWords(string s) {
int le = s.size()-1;
int ri = s.size()-1;
reverse(s.begin(), s.end());
string newStr;
while (le >= 0)
{
if (le == 0)
{
newStr.append(s.substr(0, ri - le + 1));
}
else if (s[le] == ' ')
{
newStr.append(s.substr(le+1, ri - le) + " ");
ri = le-1;
}
le--;
}
return newStr;
}
};
优化方案:
class Solution {
public:
string reverseWords(string& s) {
int i = 0;
for (int j = 0; j < s.size(); ++j) {
if (s[j] == ' ') {
reverse(s.begin() + i, s.begin() + j);
i = j + 1;
}
}
reverse(s.begin() + i, s.end());
return s;
}
};