在无序的电话号码中找到重复的并按顺序输出,比较懒,没想到什么好方法。首先把输入的电话号码都存起来转化成标准格式,然后进行快排qsort,最后比较有序的电话号码,如果有重复就输出。这里要注意比较的过程中,如果最后的几个电话相同,可能就不会输出(跳出了for循环),因此需要检查在for循环退出时cnt是否为一。代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char dict[] = {'2', '2', '2', '3', '3', '3', '4',
'4', '4', '5', '5', '5', '6', '6',
'6', '7', '0', '7', '7', '8',
'8', '8', '9', '9', '9', '0'};
int compare(const void *strA, const void *strB)
{
return strcmp(strA, strB);
}
int main()
{
int num;
int i, j, k;
char str[50], temp[9];
int cnt, flag = 0;
scanf("%d", &num);
{
char phone[num][9];
for(i = 0; i < num; i++)
{
scanf("%s", str);
for(j = 0, k = 0; str[j] != '\0'; j++)
{
if(str[j] >= '0' && str[j] <= '9')
phone[i][k++] = str[j];
else if(str[j] >= 'A' && str[j] <= 'Z')
phone[i][k++] = dict[str[j]-'A'];
if(k == 3)
phone[i][k++] = '-';
}
phone[i][k] = '\0';
}
qsort(phone, num, 9, compare);
memcpy(temp, phone[0], 9);
for(i = 1, cnt = 1; i < num; i++)
{
if(strcmp(temp, phone[i]) == 0)
cnt++;
else if(cnt != 1)
{
flag = 1;
printf("%s %d\n", temp, cnt);
memcpy(temp, phone[i], 9);
cnt = 1;
}
else
memcpy(temp, phone[i], 9);
}
if(cnt != 1)
{
flag = 1;
printf("%s %d\n", temp, cnt);
}
if(flag == 0)
printf("No duplicates.\n");
}
return 0;
}
本文介绍了一种方法,通过将输入的电话号码转化为标准格式、使用快速排序算法并比较有序的电话号码来查找并输出重复的电话号码。
778

被折叠的 条评论
为什么被折叠?



