华为机试题——HJ31 单词倒排

描述

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

说明:

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;
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值