您的位置:首页 > 编程语言 > C语言/C++

华为OJ——[中级]单词倒排

2016-07-03 20:08 295 查看
【中级】单词倒排

题目描述

对字符串中的所有单词进行倒排。

说明:

1、每个单词是以26个大写或小写英文字母构成;

2、非构成单词的字符均视为单词间隔符;

3、要求倒排后的单词间隔符以一个空格表示;如果原字符串中相邻单词间有多个间隔符时,倒排转换后也只允许出现一个空格间隔符;

4、每个单词最长20个字母;

[b]输入描述:[/b]
输入一行以空格来分隔的句子

[b]输出描述:[/b]
输出句子的逆序

[b]输入例子:[/b]
I am a student
[b]输出例子:[/b]
student a am I
解答代码:

#include<iostream>
#include<fstream>
#include<vector>
#include<cstring>
#include<string>
#include <cmath>
#include<cstdio>
#include<algorithm>
#define N 1024
using namespace std;

int main()
{
//freopen("input.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
string s;
int length,i;
string words;
while(getline(cin,s))
{
length=s.length();
words="";
//开始处理
for(i=length-1; i>-1; i--)
{
if((s[i]>='a'&&s[i]<='z') || (s[i]>='A'&&s[i]<='Z'))
{
words+=s[i];
if(words.length()==20)
{
reverse(words.begin(),words.end());
cout<<words;
if(i!=0 && s[i-1]!=' ')
cout<<' ';
words="";
}
}
else
{
reverse(words.begin(),words.end());
cout<<words;
if(i!=0 && s[i-1]!=' ')
cout<<' ';
words="";
}
}
if(words.length()>0)
{
reverse(words.begin(),words.end());
cout<<words;
}
cout<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ C语言 OJ 算法 华为