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

题目
给定一个字符串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;
}

最近更新

  1. TCP协议是安全的吗?

    2023-12-10 13:38:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-10 13:38:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-10 13:38:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-10 13:38:01       20 阅读

热门阅读

  1. react

    react

    2023-12-10 13:38:01      37 阅读
  2. 软考 系统架构设计师系列知识点之大数据(3)

    2023-12-10 13:38:01       41 阅读
  3. C++知识 抽象基类

    2023-12-10 13:38:01       41 阅读
  4. CSS中的水平垂直居中元素的多种方式

    2023-12-10 13:38:01       46 阅读
  5. 高防IP防御效果怎么样,和VPN有区别吗

    2023-12-10 13:38:01       35 阅读
  6. Metasploit在蓝队防御中的应用

    2023-12-10 13:38:01       25 阅读
  7. Tmux中使用Docker报错 - 解决方案

    2023-12-10 13:38:01       40 阅读
  8. ubuntu串口永久权限

    2023-12-10 13:38:01       36 阅读
  9. Http常见的状态码

    2023-12-10 13:38:01       29 阅读
  10. 函数的参数

    2023-12-10 13:38:01       34 阅读