https://oj.leetcode.com/problems/reverse-words-in-a-string/
1、题目要求:将字符串s里面的单词逆序排列;
注:如果字符串s开始和结尾处有多余的空格,则删除;
如果单词之间有多余的字符串,则删除;
例:假设s=" the sky is blue ",则返回"blue is sky the"——单词逆序,单词本身(blue)没有逆序
2、解题思路:对于字符串AB,如果把AB分别逆序,即A',B',再把(A'B')逆序,即(A'B')',得到BA;这正是题目所要求的。
3、解题步骤
step1:分别用两个栈来存放单词word和字符串sentence;
step2:先将每个单词word逆序压入sentence里面;
step3:再将sentence弹出,实现对其逆序;
<span style="font-family:Arial;">class Solution{
public:
void reverseWords(string &s){
stack<int> word;
stack<int> sentence;
for (string::size_type i = 0; i != s.size(); i++)
{
if(!isspace(s[i])) //将每个单词存进单词栈中
{
word.push(s[i]);
}
if (isspace(s[i]) || (i == s.size()-1))
{
while(!word.empty()) //将单词栈中的元素逆序存进句子栈
{
sentence.push(word.top());
word.pop();
if (word.empty()) //在每个单词后面插入一个空格
sentence.push(' ');
}
}
}
if (!sentence.empty()) //删除句子栈中的最后插入的一个空格,注意考虑输入为空字符串的情况
sentence.pop();
s.clear();
while (!sentence.empty()) //逆序输出句子栈中元素
{
s.push_back(sentence.top());
sentence.pop();
}
}
};