问题描述:
Given an input string, reverse the string word by word.
For example,Given s = "the sky is blue",
return "blue is sky the".
解题思路:
每遍历出一个单词时,将该单词添加一个空格字符(如果临时字符串为空,即扫描出第一个单词,就不要添加空格字符),然后添加到一个临时字符串的首部。所以时间复杂度和空间复杂度都为O(n)。
需要注意的条件:遍历不要超出字符串长度。
class Solution {
public:
void reverseWords(string &s) {
int length = s.size();
if (0 == length)
return;
string substr, temp;
substr = temp = "\0";
int i = 0, pos;
while (i < length)
{
while (' ' == s[i] && i < length) /* 过滤字符之间的空格 */
i++;
if (i == length) /* 所有字符全部处理完 */
break;
pos = i;
while (s[i] != ' ' && i < length)/* 找到下一个要处理的单词 */
i++;
substr = s.substr(pos, i-pos);/* 获取要处理的单词 */
if (temp.size() > 0)
substr += " " + temp;
temp = substr;
}
s = temp;
}
};