问题描述
输入n个字符串,比较这些字符串的大小并统计并按字典序输出字符串及出现个数
输入格式
输入的第一行包含一个整数n,表示字符串个数。接下来n行,表示输入的字符串。
输出格式
输出n行,每行包含一个字符串及一个整数,表示字符串及出现个数。
样例输入
5
aab
bbc
aab
sdffg
sgjklsa
样例输出
aab 2
bbc 1
sdffg 1
sgjklsa 1
这道题感觉给的答案是错误的
。。。
还是写一下吧,思路:字典序排序然后去重
//字符串比大小
#include <iostream>
#include <algorithm>
using namespace std;
struct node{
string s;
int num;
}p[1000];
int n;
bool cmp(node x,node y)
{
int t1 = x.s.size();
int t2 = y.s.size();
return x.s.compare(y.s)<0; // 字典序排序使用compare函数
}
int main()
{
scanf("%d",&n);
for(int i =1;i<=n;i++)
{
cin>>p[i].s;
p[i].num = 1;
}
sort(p+1,p+1+n,cmp);
int cnt=1;
for(int i =2;i<=n;i++) //去重操作
{
if(p[i].s.compare(p[i-1].s)==0)
{
p[cnt].num++;
}
else
{
p[++cnt] = p[i];
}
}
for(int i =1;i<=cnt;i++)
{
cout<<p[i].s<<" "<<p[i].num<<endl;
}
return 0;
}