剑指OFFER 翻转单词顺序列
思路都是先把一个个单词提取出来,对所有单词进行倒序,
c++
class Solution {
public:
string ReverseSentence(string str) {
if(str.size()==0)return string("");
stack s;
string word;
string res;
int str_size = str.size();
for(int i=0;i
{
if(str[i]==' ' || i == str_size-1)
{
if(i == str_size - 1)
{
word += str[i];
}
s.push(word);
word.clear();
continue;
}
word += str[i];
}
while(!s.empty())
{
res += s.top() + ' ';
s.pop();
}
res.erase(res.size()-1);//去掉后面的空格
return res;
}
};
python
# -*- coding:utf-8 -*-
class Solution:
def ReverseSentence(self, s):
# write code here
words = s.split(' ');
print words
res = ""
new_words = words[::-1]
for word in new_words:
res = res + " " + word
res = res[1:]
return res