描述
对字符串中的所有单词进行倒排。
说明:
1、构成单词的字符只有26个大写或小写英文字母;
2、非构成单词的字符均视为单词间隔符;
3、要求倒排后的单词间隔符以一个空格表示;如果原字符串中相邻单词间有多个间隔符时,倒排转换后也只允许出现一个空格间隔符;
4、每个单词最长20个字母;
数据范围:字符串长度满足 1 \le n \le 10000 \1≤n≤10000
输入描述:
输入一行,表示用来倒排的句子
输出描述:
输出句子的倒排结果
示例1
输入:
I am a student
复制输出:
student a am I
复制
示例2
输入:
$bo*y gi!r#l
复制输出:
l r gi y bo
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <string.h>
#include <malloc.h>
#include <sstream>
#include <algorithm>
#include <cstring>
#include <map>
#include <set>
#include <vector>
void print(std::vector<std::string> strVect)
{
for(int i = 0; i < strVect.size(); ++i)
{
std::cout << strVect.at(i) << " ";
}
std::cout << std::endl;
}
void print(std::string str)
{
for(int i = 0; i < strlen(str.c_str()); ++i)
{
std::cout << str[i];
}
std::cout << std::endl;
}
void WordReverse(std::string str)
{
std::string copyStr(str);
std::vector<std::string> strVect;
int len = strlen(str.c_str());
int i = 0;
while(str[i] != '\0')
{
int tempc = str[i];
if((tempc >= 65 && tempc <= 90) || (tempc >= 97 && tempc <= 122)) //说明是字母
{
++i;
}
else
{
str[i] = ' ';
i++;
}
}
i = 0;
int index = 0;
while(index != -1)
{
index = str.find(' ');
std::string temp = str.substr(0, index);
strVect.push_back(temp);
str = str.substr(index + 1, len - strlen(temp.c_str() - 1));
i++;
}
std::reverse(strVect.begin(), strVect.end());
print(strVect);
}
int main()
{
std::string str = "$bo*y gi!r#l"; //输出 l r gi y bo
getline(std::cin, str);
WordReverse(str);
return 0;
}