题目链接:https://leetcode.com/problems/reverse-words-in-a-string/
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.
思路:如果利用C++的istringstream类将字符串以空格分开,将会使得题目变得极其简单,但是这并不是这题的目的,这题考察的就是操作数组的能力,也就是不能使用额外的空间。曾经面试过百度,让我替换字符串中的空格,如果允许开额外的空间或者允许使用string的函数,也将变得极为简单,但是他并不让用。
好吧,如果我们做原地翻转字符串,那么我们要首先对字符串中的单词就地翻转一次,然后再将总的字符串翻转一次。但是麻烦的是开头,结尾,中间都会有多余的空格,因此,本题考察的其实就是去除烦人的空格。
第一种使用istringstream的解决方案时间复杂度是O(n),空间复杂度是O(n)
第二种就地翻转的解决方案时间复杂度是O(n),空间复杂度是O(1)
两种代码如下:
class Solution {
public:
void reverseWords(string &s) {
istringstream is(s);
s.clear();
string tem;
while(is >> tem)
s = tem + " " + s;
s = s.substr(0, s.size()-1);//因为尾部多了一个空格
}
};
参考:https://leetcode.com/discuss/65766/c-5lines-o-1-space
class Solution {
public:
void reverseWords(string &s) {
if(s.size() ==0) return;
int left = 0, right = 0, i =0;
while(i < s.size())
{
while(i < s.size() && s[i] == ' ') i++;
if(i >= s.size()) break;
if(left != right) s[right++] = ' ';
left = right;
while(i< s.size() && s[i] != ' ') s[right++] = s[i++];
reverse(s.begin()+left, s.begin()+right);
}
s.resize(right);
reverse(s.begin(), s.end());
}
};
参考:https://leetcode.com/discuss/16669/c-solution-in-place-runtime-o-n-memory-o-1