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.
// 主要用到两个字符串,string t,res,扫描整个字符串,将单词copy to t.如果,遇到空格,将cache t字符串copy to res
// 重复上面的步骤,直到i = s.length,最后一步就是temp可能包含字符串,所以,再次copy to res.
// 时间复杂度 O(n) 空间复杂度 O(1). 这题已经AC.
class Solution {
public:
void reverseWords(std::string &s) {
std::string t = "",res = "";
for(std::string::size_type i = 0; i < s.length(); i++)
{
if(s[i] == ' ')
{
res = t + (t == ""||res ==""?"":" ") + res;
t = "";
}
else
{
t += s[i];
}
}
s = t + (t == ""||res == ""?"":" ") + res;
std::cout << s << std::endl;
}
};