字符串排序II【北京大学考研机试题】

字符串排序II

编写一个程序,将输入字符串中的字符按如下规则排序。

  • 规则 1:英文字母从 A 到 Z 排列,不区分大小写。如,输入:Type 输出:epTy。
  • 规则 2:同一个英文字母的大小写同时存在时,按照输入顺序排列。如,输入:BabA 输出:aABb。
  • 规则 3:非英文字母的其它字符保持原来的位置。如,输入:By?e 输出:Be?y。
    输入格式
    输入包含多组测试数据。

每组数据占一行,包含一个字符串。

输出格式
每组数据输出一行结果,为按要求排序后的字符串。

数据范围
字符串长度不超过 1000,
每个输入最多包含 100 组数据。

输入样例:
A Famous Saying: Much Ado About Nothing (2012/8).
输出样例:
A aaAAbc dFgghh: iimM nNn oooos Sttuuuy (2012/8).

代码

点击查看代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<cctype>
using namespace std;

#define X first
#define Y second

typedef pair<int,int> pii;
typedef pair<char,char> pcc;
typedef long long LL;
const char nl = '\n';
const int N = 1e6+10;
const int M = 2e5+10;
int n,m;

void solve(){
	string s;
	string t = "";
	while(getline(cin,s)){
		vector<string> v_others;
		vector<char> v_alpha,v_alpha1;
		vector<int> v_cnt;
		int cnt = 0;
		t = "";
		for(auto c:s){
			if(isalpha(c)){
				if(t.size())v_others.push_back(t);
				v_alpha1.push_back({c});
				t = "";
				cnt ++;
			}
			else{
				if(cnt)v_cnt.push_back(cnt);
				cnt = 0;
				t += c;
			}
		}
		if(t.size())v_others.push_back(t);
		if(cnt)v_cnt.push_back(cnt);
		//sort(v_alpha.begin(), v_alpha.end());//
		for(char i = 'a'; i <= 'z'; i ++ ){
			for(auto u:v_alpha1){
				if(u == i || u == toupper(i))v_alpha.push_back(u);
			}
		}
		reverse(v_cnt.begin(), v_cnt.end());
		reverse(v_alpha.begin(), v_alpha.end());
		reverse(v_others.begin(), v_others.end());
		if(isalpha(s[0])){
			while(v_cnt.size()){
				auto k = v_cnt.back();
				v_cnt.pop_back();
				while(k -- && v_alpha.size()){
					auto u = v_alpha.back();
					v_alpha.pop_back();
					cout << u;
				}
				if(v_others.size()){
					auto p = v_others.back();
					v_others.pop_back();
					cout << p;
				}
			}
			while(v_alpha.size()){
				auto u = v_alpha.back();
				v_alpha.pop_back();
				cout << u;
			}
			while(v_others.size()){
				auto p = v_others.back();
				v_others.pop_back();
				cout << p;
			}
		}
		else{
			while(v_cnt.size()){
				if(v_others.size()){
					auto p = v_others.back();
					v_others.pop_back();
					cout << p;
				}
				auto k = v_cnt.back();
				v_cnt.pop_back();
				while(k -- && v_alpha.size()){
					auto u = v_alpha.back();
					v_alpha.pop_back();
					cout << u;
				}
			}
			while(v_alpha.size()){
				auto u = v_alpha.back();
				v_alpha.pop_back();
				cout << u;
			}
			while(v_others.size()){
				auto p = v_others.back();
				v_others.pop_back();
				cout << p;
			}
		}
		cout << nl;
	}
}

int main(){
	ios::sync_with_stdio(false);
	cin.tie(0),cout.tie(0);

	solve();
}

注意

  1. 多组数据输入记得每次都要初始化,注意换行
  2. 排序可以根据字母顺序排
  3. 一定要不重不漏地输出
  4. 其实位置不变的话直接s[i] = c,然后将排序号的字母放入原本是字母的位置即可,这里写麻烦了
posted @ 2023-03-06 16:31  Keith-  阅读(20)  评论(0编辑  收藏  举报