PAT 乙级 1009 (方法 + 代码)

1009 说反话 (20 分)

给定一句英语,要求你编写程序,将句中所有单词的顺序颠倒输出。

输入格式:

测试输入包含一个测试用例,在一行内给出总长度不超过 80 的字符串。字符串由若干单词和若干空格组成,其中单词是由英文字母(大小写有区分)组成的字符串,单词之间用 1 个空格分开,输入保证句子末尾没有多余的空格。

输出格式:

每个测试用例的输出占一行,输出倒序后的句子。

输入样例:

Hello World Here I Come

输出样例:

Come I Here World Hello

解题思路:(三种)

C++版

第一种:利用stack种栈的先进后出的原理
#include<iostream>
#include<stack>
#include<string>
using namespace std;

int main()
{
	stack<string> ch;
	string s;
	while(cin>>s)
		ch.push(s); 
	cout<<ch.top();
	ch.pop();
	while(!ch.empty())
	{
		cout<<' '<<ch.top();
		ch.pop();
	}
	//system("pause");
	return 0;
}
第二种:利用vector容器
#include<iostream>
#include<stdlib.h>
#include<string>
#include<vector>
using namespace std;
int main()
{
	string ch;
	vector<string> a;
	while(cin>>ch)
	{
		a.push_back(ch);
	}
	int num = a.size();
	cout<<a[num - 1];
	for(int i = num -2; i >= 0; i-- )
	{
		cout<<' '<<a[i];
	}
	return 0;
}
第三种:利用map键值对
#include<iostream>
#include<stdlib.h>
#include<string>
#include<map>

using namespace std;

int main()
{
	string ch;
	map<int,string> a;
	int l = 0;
	while(cin>>ch)
	{
		a[l] = ch;
		l++;
	}
	for(auto it = a.rbegin();it != a.rend();it++)
	{
		if(it == a.rbegin())
			cout<<it->second;
		else
			cout<<' '<<it->second;
		
		
	}
	system("pause");
	return 0;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值