题目:
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.
思路:
刷题刷久了,就忘了面试中关键的一个考察点,就是对一个题目有疑惑的时候,一定要记得和面试官讨论,进行clarification。上面写到的三点clarification都是非常重要的,直接关系到代码该怎么写。
其实算法的思路也算是比较明确的:1)每当检测出来一个单词时,对其进行翻转;2)当所有的单词被检测出来时,对整个字符串再进行一次翻转。由于原字符串中有可能存在多余的空格,所以我们在扫描过程中,需要在字符串内部进行复制,以将多余的空格给覆盖掉。具体见下面的代码片段。该思路的时间复杂度是O(n),空间复杂度是O(1)。
代码:
class Solution {
public:
void reverseWords(string &s) {
int len = s.size();
int left = 0, right = 0, i = 0, flag = false;
while(i < len) {
while(s[i] == ' ') // trim the leading space
i++;
if(i == len) // already at the end
break;
if(flag)
s[right++] = ' ';
left = right;
while(i < len && s[i] != ' ')
s[right++] = s[i++];
reverse(s, left, right-1);
flag = true; // flag is used to judge whether append " "
}
s.resize(right);
reverse(s, 0, right - 1);
}
private:
void reverse(string&s, int left, int right) {
while(left < right) {
char ch = s[right];
s[right--] = s[left];
s[left++] = ch;
}
}
};
这篇解题报告介绍了如何解决LeetCode上的151题——翻转字符串中的单词。题目要求在O(1)空间复杂度内完成,且要考虑字符串中的多余空格。解题思路包括检测单词并翻转,以及最后对整个字符串的翻转,确保不包含多余前导或尾随空格。
406

被折叠的 条评论
为什么被折叠?



