问题描述
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue"
,
return "blue is sky the"
.
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
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.
思路分析
将一个字符串中的单词反序输出。字符串中词与词之间可能有多个空格。
使用两个指针,思路分为三步:第一步是去除多余的空格,利用快指针i遍历,找到下一个单词,然后慢指针j用来构建新的字符串;如果i跑出了s的范围,循环结束。第二步,将每个单词逆序,记录新字符串单词的开始位置,然后将其reverse;在下一个循环,j开始新单词之前插入空格‘ ’。第三步,将整个字符串翻转。
代码
class Solution {
public:
void reverseWords(string &s) {
int length = s.length();
int i = 0, j = 0;
while (true){
while (i < length && s[i] == ' ') i++;
if (i >= length) break;
if (j > 0) s[j++] = ' ';
int start = j;
while (i < length && s[i] != ' '){
s[j++] = s[i++];
}
reverse(s.begin() + start, s.begin() + j);
}
s.resize(j);
reverse(s.begin(), s.end());
}
};
时间复杂度:
O(n)
空间复杂度:
O(1)
反思
心情也是挺日狗的,medium的题就能把我难住,自己对于问题的抽象理解能力还不是很到位,没找到问题的关键——使用两个指针这样的方法。
对于问题,首先是考虑需要进行的操作,然后考虑的是这样的操作我可以用什么样的方法来实现,使用什么样的编程方式和技巧。