做题感悟:
开始做这题时就是完全的暴力,很显然超时。之后又听说 map 可以搞定这一题,于是乎学 map 今天搞了一天 map 终于把 map 给搞懂了。其实这题还可以用另一种方法,把电话号码映射成一个数字(数字7位)。应该想到的……
题意:
给你许多字符(包括大写字母,数字,‘-’),经过某种转换,都可以转换成一个七位的电话号码。让你输出重复的电话号码超过两次的电话号码。没有输出:No duplicates.
解题思路:
用 map 容器存,map的用法(见知识点积累)。
代码:
#include<stdio.h>
#include<string.h>
#include<map>
#include<iostream>
#include<string>
using namespace std ;
string str ;
char s[100] ;
int check(char ch) // 转化
{
switch(ch)
{
case 'A' :
case 'B' :
case 'C' : return '2' ;
case 'D' :
case 'E' :
case 'F' : return '3' ;
case 'G' :
case 'H' :
case 'I' : return '4' ;
case 'J' :
case 'K' :
case 'L' : return '5' ;
case 'M' :
case 'N' :
case 'O' : return '6' ;
case 'P' :
case 'R' :
case 'S' : return '7' ;
case 'T' :
case 'U' :
case 'V' : return '8' ;
case 'W' :
case 'X' :
case 'Y' : return '9' ;
default : return '-' ;
}
}
int main()
{
int T,h,t,i ;
char ch ;
map<string,int>m ;
map<string,int>::iterator start ;
scanf("%d",&T) ;
while(T--)
{
scanf("%s",s) ;
h=strlen(s) ;
t=0 ;
str="" ;
int flag=1 ;
for(i=0 ;i<h ;i++)
{
if(s[i]>='A'&&str[i]<='Y'&&str[i]!='Q')
{
ch=check(s[i]) ;
if(ch!='-')
{
str+=ch ;
t++ ;
}
}
else if(s[i]>='0'&&s[i]<='9')
{
str+=s[i] ;
t++ ;
}
if(t==3&&flag)
{
str+='-' ;
flag=0 ;
}
}
m[str]++ ;
}
int f=0 ;
for(start=m.begin() ;start!=m.end() ;start++)
{
if(start->second>1)
{
cout<<start->first<<" "<<start->second<<endl ;
f=1 ;
}
}
if(!f) printf("No duplicates.\n") ;
m.clear() ;
return 0 ;
}