剑指offer第44题
翻转单词顺序列
http://www.nowcoder.com/questionTerminal/3194a4f4cf814f63919d0790578d51f3
很少看到用c++的,这里给个解法
注意这道题有个坑,要求转换后的字符串空格数和转换前保持一致。
就不能像java和python那样直接把空格split掉,然后再用空格把单词连接起来就行。
class Solution {
public:
string ReverseSentence(string str) {
string ans;
int length = str.size();
//字符串为空则返回为空
if(length == 0) return ans;
vector<string> tmp_ans;//用来保存提取的单词和空格
int i = 0;
while(i < length){
string tmp1;//临时存放单词
int j = i;
while(j < length && str[j] != ' '){
tmp1.push_back(str[j]);
++j;
}
if(!tmp1.empty()){
tmp_ans.push_back(tmp1);
}
string tmp2;//临时存放空格,包括连续的空格或者输入字符串为多个空格的情况
while(str[j] == ' '){
tmp2.push_back(' ');
++j;
}
tmp_ans.push_back(tmp2);
i = j;
}
for(int i = tmp_ans.size() - 1; i >= 0; --i){
ans.append(tmp_ans[i]);
}
return ans;
}
};