做題感悟:
開始做這題時就是完全的暴力,很顯然超時。之後又聽說 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 ; }