华为机试真题 C++ 实现【字符串重新排列】

本文介绍了一个C++程序,它接受一个字符串作为输入,首先对每个单词内部的字母进行字典序排序,然后根据单词出现的次数和长度进行降序和升序排列。程序使用了unordered_map和vector等数据结构实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目
给定一个字符串s,s包括以空格分隔的若干个单词,请对s进行如下处理后输出:

1、单词内部调整:对每个单词字母重新按字典序排序

2、单词间顺序调整:

1)统计每个单词出现的次数,并按次数降序排列

2)次数相同,按单词长度升序排列

3)次数和单词长度均相同,按字典升序排列

请输出处理后的字符串,每个单词以一个空格分隔。

输入描述:
一行字符串,每个字符取值范围:【a-zA-z0-9】以及空格,字符串长度范围:【1,1000】

例1:

输入

This is an apple

输出

an is This aelpp

例2:

输入:

My sister is in the house not in the yard

输出:

in in eht eht My is not adry ehosu eirsst

#include <cstdio>
#include <iostream>
#include <unordered_map>
#include <algorithm>
#include <string>
#include <map>
#include <vector>

using namespace std;

bool cmp(pair<string, int> it1, pair<string, int> it2){
	if(it1.second == it2.second){
		if(it1.first.length() == it2.first.length()){
			return it1.first < it2.first;
		}else{
			return it1.first.length() < it2.first.length();
		}
	}else{
		return it1.second > it2.second;
	}
}

int main(){
	string word;
	map<string, int> all_cnt;

	while(cin >> word){
		sort(word.begin(), word.end());
		all_cnt[word]+= 1;
		word.clear();
	}
	
	vector<pair<string, int> > vecWords(all_cnt.begin(), all_cnt.end());
	sort(vecWords.begin(), vecWords.end(), cmp);

	bool first = true;
	int n = vecWords.size();
	for(int i = 0; i < n;i++){
		pair<string, int> use_pair = vecWords[i];
		for(int j = 0; j < use_pair.second;j++){
			if(first){
				first = false;
				cout << use_pair.first;
			}else{
				cout << " " << use_pair.first;
			}
		}
	}
	cout << endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值