题目如下:
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
分析如下:
很基础的题目,需要考虑各种corner cases,比如下列:
1 " "
2"a "
3" a "
4" a"
5" a b "
6" a b "
7" a b"
8"a b "
9" a b c d e f g "
我的代码:
// 20ms过大集合
class Solution {
public:
void reverseWords(string &s) {
vector<string> vec;
int len=(int)s.length();
if(len==0)
return;
int i=0;
int j=len-1;
while(i!=len&&s[i]==' ')
i++;
while(j!=-1&&s[j]==' ')
j--;
int k=i;
while(i<=j){
k=i;
while(s[i]!=' '&&i<=j)
i++;
vec.push_back(s.substr(k,i-k));
while(s[i]==' '&&i<=j)
i++;
}
if(vec.empty()){
s="";
return;
}
reverse(vec.begin(),vec.begin()+vec.size());
string m=vec[0];
for(int i=1;i<vec.size();i++){
m+=" ";
m+=vec[i];
}
s=m;
}
};
小结扩展:
(1) 之前有道相关的题目,在这篇文章的“小结扩展1“这里
updated-2014-11-16:
class Solution {
public:
void reverseWords(string &s) {
// preprocess 1 去空串
if (s == "")
return;
int i = 0;
// preprocess 2 去全空白串。" "
while(i < s.length() && s[i] == ' ')
i++;
if (i == s.length()) {
s = "";
return ;
}
// start work
string word;
istringstream str_stream(s);
string res = "";
while(str_stream >> word) {
//if (word == "") continue; // str_stream>>word会挤掉单词之间的所有的空格符,不管是1个还是N个,这句没有必要
res = " " + word + res;
}
s = res.substr(1);
return;
}
};
上面的时间复杂度是 2 * o(n),第1个o(n)预处理,第2个o(n)去真正干活。预处理做的主要事情是如果输入字符串全部都是" ",则不能走入while循环,否则报错。
暂时没有找到什么办法可以在1 * o(n)的时间完成。