题目要求:
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
Clarification:
- What constitutes a word?
A sequence of non-space characters constitutes a word. - Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces. - How about multiple spaces between two words?
Reduce them to a single space in the reversed string
我是用c++ 写的:
class Solution {
public:
void reverseWords(string &s) {
size_t idx_start = 0;
size_t idx_end;
//erase the space at head and trail
idx_start = s.find_first_not_of(" ");
s.erase(0, idx_start);
idx_end = s.find_last_not_of(" ");
s.erase(idx_end + 1);
reverse(s.begin(), s.end());
idx_start = 0;
string ret;
string tmp;
while(true)
{
tmp.clear();
idx_end = s.find(' ', idx_start);
if(idx_end == string::npos)
break;
//deal the sitution of contiguous spaces like " "
if(s[idx_start] == ' ')
{
idx_start = idx_end + 1;
continue;
}
tmp = s.substr(idx_start, idx_end - idx_start);
reverse(tmp.begin(), tmp.end());
ret.append(tmp);
ret.append(" ");
idx_start = idx_end + 1;
}
//reverse the last word
tmp = s.substr(idx_start);
reverse(tmp.begin(), tmp.end());
ret.append(tmp);
s = ret;
}
};