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.
思路:题目不难,但是题目要求空间复杂度为O(1),这就要费些脑子,先看看空间复杂度非O(1)的代码,一次遍历。
class Solution {
public:
void reverseWords(string &s) {
string t = "";
int i = 0,j;
int len = s.length();
while(i < len){
while(i < len && isblank(s[i]))
i++;
if(i == len){
s = t.substr(0, t.length()-1);
return;
}
j = i;
while(j < len && !isblank(s[j]))
j++;
t = s.substr(i, j-i) + " " + t;
i = j;
}
s = t.substr(0, t.length()-1);
}
};
空间复杂度为O(1)的思路是:
(1)去除字符串首尾的空白,同时是的单词之间只有一个空格,得到字符串s
(2)从后向前遍历s,保存倒数第二个单词,同时倒数第一个单词向前移动倒数第二个单词长度的距离,然后在最后一个单词后面加入倒数第二个单词(中间有空个),之后一次类推。(例如s=”the sky is blue”,第一次移动后s=”the sky blue is”(bule向前移动,is加到blue后面),第二次移动后s=”the blue is sky”(bule is向前移动,sky加到is后面),第三次移动后s=”blue is sky the”(bule is sky向前移动,the加到sky后面))
(3)重复(2)直到整个字符串反转。
class Solution {
public:
void reverseWords(string &s) {
int len = s.length();
int i = 0, j = len - 1, k;
while(i < len){//去掉头的空格
if(isblank(s[i]))
i++;
else
break;
}
while(j >= 0){//去掉尾的空格
if(isblank(s[j]))
j--;
else
break;
}
s = s.substr(i, j - i + 1);
for(i = 0; i < s.length(); ++i){//使得单词之间只有一个空格
if(isblank(s[i])){
j = i;
while(i < s.length() && isblank(s[i])){
i++;
}
if(i - j > 1)
s = s.substr(0, j+1) + s.substr(i, s.length() - i);
i-=i-j;
}
}
len = s.length();
i = j = len - 1;
while (i >= 0) {
while(i >= 0 && !isblank(s[i])) {
i--;
}
if (j == len - 1)
j = i;
else {
string tmp;
if(i < 0)
tmp = " " + s.substr(0, j);
else
tmp = s.substr(i, j - i);
for (k = i + 1; k + j - i< len; k++)
s[k] = s[k + j - i];
for (k = len - (j - i); k < len; ++k)
s[k] = tmp[j - i + k - len];
j = i;
}
i--;
}
}
};