题目选自PTA基础编程题目集7-32
题目描述:
给定一句英语,要求你编写程序,将句中所有单词的顺序颠倒输出。
输入格式:
测试输入包含一个测试用例,在一行内给出总长度不超过500 000的字符串。字符串由若干单词和若干空格组成,其中单词是由英文字母(大小写有区分)组成的字符串,单词之间用若干个空格分开。
输出格式:
每个测试用例的输出占一行,输出倒序后的句子,并且保证单词间只有1个空格。
样例:">样例:">输入样例:
Hello World Here I Come
输出样例:
Come I Here World Hello
解题思路:考虑使用栈(栈为字符串类型的栈)的方法,读完一个单词就入栈,输出的时候依次出栈即可
代码:
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main(){
//获取整个字符串
string str;
getline(cin,str);
stack<string> st; //存储字符串的栈
string temp = "";
for(int i=0;i<str.size();i++){
if(str[i]=='\n'){ //读完跳出
break;
}
if(str[i]!=' '){ //若当前字符不为空格,则并入字符串
temp+=str[i];
}else{ //若当前为空格,则说明读取一个单词完毕,入栈
st.push(temp); //若栈顶为空格,则空格出栈
if(st.top()==""){
st.pop();
}
temp=""; //初始化字符串
}
}
st.push(temp); //由于最后是 '\n' 未能及时进栈,所以最后一个单词在此进栈
if(st.top()==""){ //若最后一个单词也为空格,则出栈
st.pop();
}
int k=st.size();
int i=0;
while(!st.empty()){ //控制输出格式
if(i==k-1){
cout<<st.top();
st.pop();
}else{
if(st.top()==""){
st.pop();
}
cout<<st.top()<<" ";
st.pop();
}
i++;
}
return 0;
}
结果: