思路很简单,但实现起来犯了很多错误。
思路: 读入每个号码的同时,将其转换为标准形式存储在数组中。排序。顺序遍历整个数组,由于已经排好序,则相同的号码一定相邻,计算其个数并输出即可。
问题:
- sort函数不能对字符串数组排序,只能对string数组排序。
- 遍历并输出的过程有很多细节出错。
string类的一些细节: string可以像字符串那样按下标访问,其中的一位如s[0]就是一个字符。可以把字符串直接赋值给string。对string的操作尽量要使用STL中的函数。
#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
string res[100010];
char temp[100],str[100];
int main() {
int n;
scanf("%d",&n);
char trans[100];//转换为标准形式
trans['A']=trans['B']=trans['C']='2';
trans['D']=trans['E']=trans['F']='3';
trans['G']=trans['H']=trans['I']='4';
trans['J']=trans['K']=trans['L']='5';
trans['M']=trans['N']=trans['O']='6';
trans['P']=trans['R']=trans['S']='7';
trans['T']=trans['U']=trans['V']='8';
trans['W']=trans['X']=trans['Y']='9';
for(int i=0; i<n; i++) {
scanf("%s",str);
int j=0,k=0;
for(; str[j]!=0; j++) {
if(str[j]>='0'&&str[j]<='9') temp[k++]=str[j];
else if(str[j]>='A'&&str[j]<='Z') {
temp[k++]=trans[str[j]];
}
}
temp[k]='\0';
res[i]=temp;//字符串数组可以直接赋值给string
}
sort(res,res+n);
//for(int i=0; i<n; i++) cout<<res[i]<<endl;
bool flag=true;
for(int i=1,k=0; i<n; i++) {
if(res[i]!=res[k]) {//固定k,i往前走,直到找到一个不相等的string
if(i-k>1) {//重复的个数大于1
printf("%c%c%c-%c%c%c%c %d\n",res[k][0],res[k][1],res[k][2],res[k][3],res[k][4],res[k][5],res[k][6],i-k);
flag=false;
}
k=i;//每找到一个不相等的,就更新k,然后i继续向前推进
}
else if(i==n-1) {
printf("%c%c%c-%c%c%c%c %d\n",res[k][0],res[k][1],res[k][2],res[k][3],res[k][4],res[k][5],res[k][6],i-k+1);
flag=false;
}
}
if(flag==true) printf("No duplicates.");
return 0;
}