字符排序
Problem ID: 1382
Contest ID: 6049
必做题
时间限制:1s 空间限制:64M
题目描述:
输入一行包含空格的字符串,请按字符的 ASCII 码由小到大的顺序自左到右地排列,并过滤掉空格输出。
输入格式:
一行包含空格的字符串。(字符最多可达100000个)
输出格式:
排序后的字符。
样例输入:
I am a boy
样例输出:
Iaabmoy
Problem ID: 1382
Contest ID: 6049
必做题
输入一行包含空格的字符串,请按字符的 ASCII 码由小到大的顺序自左到右地排列,并过滤掉空格输出。
一行包含空格的字符串。(字符最多可达100000个)
排序后的字符。
I am a boy
Iaabmoy
思路
在线等
遍历一遍字符串,如果是空格就跳过,其他的就正常的比大小
#include <bits/stdc++.h>
using namespace std;
int main(){
int a[128]={0};
string s;
getline(cin,s);
for(int i=0;i<s.size();i++){
if(s[i]!=' '){
a[s[i]]++;
}
}
for(int i=0;i<128;i++){
while(a[i]>0){
printf("%c",i);
a[i]--;
}
}
return 0;
}
代码如上
我记得sort好像也能排序字符的吧()
所以我直接……
#include<bits/stdc++.h>
using namespace std;
char b[100005];
int main(){
cin.get(b,100005);
sort(b,b+strlen(b));
cout<<b;
return 0;
}
就AC了awa
不对,strlen和string有版本差异,不行,有些编译器会报错,而且空格的值是32,会在最前面。
代码如下
#include<bits/stdc++.h>
using namespace std;
string a;
int main(){
getline(cin,a);
sort(a.begin(), a.end());
for(int i=0;i<a.size();i++)
if(a[i]!=' ') cout<<a[i];
}
注: a.begin() 和 a.end() 是 std::string 提供的迭代器,分别指向字符串的开始和结束。 ![]()
遍历字符串输出可以不输出空格
下次标题把题名写上
解决方案+一个赞?
![]()