百炼OJ 2974 电话号码的标准化

问题:将一连串的字符转化成用数字表示的数字串 ,如:

3234567       -----   323-4567

888-GINO      -----  888-1010

3-10-10-10    -----  310-1010

-8-2-3-5-7-2-9- --  823-5729

该问题的关键点在于去 ‘-’ 和 将对应的字符映射到数字,见代码:

 1 /************************************************************************/
 2  *        Author: bakari  
 3  *        Date :2012/6/5
 4  *        StandardPhoneNum
 5 /************************************************************************/
 6 #include <iostream>
 7 #include <string.h>
 8 #include <algorithm>
 9 using std::cout;
10 using std::cin;
11 using std::endl;
12 
13 const int STRLEN = 9;
14 const int MAXSTRLEN = 50;
15 const int MAXROW = 10000;
16 
17 char map[] = "22233344455566677778889999";  //存储映射表
18 char TranseStr[MAXROW][STRLEN];
19 //char str[MAXSTRLEN];
20 
21 int cmp (const void * elem1, const void * elem2){  //快排比较函数
22     return strcmp((char *)elem1, (char *)elem2); 
23 
24 }
25 void StandardTranse(const char *str, int n){
26 
27     for(size_t i = 0, j = 0; j < STRLEN - 1; ){
28         if(str[i] != '-'){
29             if(str[i] <= 'Z' && str[i] >= 'A')
30                 TranseStr[n][j] = map[str[i] - 'A'];
31             if(str[i] <= '9' && str[i] >= '0')
32                 TranseStr[n][j] = str[i];
33             ++ i;
34             ++ j;
35         }
36         else{
37             ++ i;
38         }
39         if(3 == j){
40             TranseStr[n][j++] = '-';
41         }
42     }
43 }
44 
45 void FindSameNum(int n){
46     int ix = 0;
47     int jx;
48     bool noduplicate = true;
49     while(ix < n){
50         jx = ix;
51         ++ ix;
52         while(ix < n && strcmp(TranseStr[ix],TranseStr[jx]) == 0)
53             ++ix;
54         if (ix - jx > 1){
55             cout << TranseStr[jx] << " " << ix - jx <<endl;
56             noduplicate = false;
57         }
58     }
59     if (noduplicate)
60         cout << "No duplicate." << endl;
61 }
62 
63 int main()
64 {
65     int n;
66     char str[MAXSTRLEN];
67     cin >> n;
68     for(int i = 0; i != n; ++i){
69         cin >> str;
70         StandardTranse(i);
71     }
72      cout << "输出" <<endl;
73     for(int i = 0; i != n; ++i)
74          cout << TranseStr[i] << endl;
75     
76     qsort(TranseStr,n,STRLEN,cmp);
77     FindSameNum(n);
78     return 0;
79 }

 

标准化函数StandardTranse()的另一个解法

 1 void StandardTranse(const char *str, int n){
 2     int j ,k;
 3     j = k = -1;
 4     while(k < STRLEN - 1){
 5         j ++;
 6         if(str[j] == '-')   //先做判断
 7             continue;
 8         k ++;
 9         if(3 == k)
10             TranseStr[n][k ++] = '-';
11         if(str[j] >= 'A' && str[j] <= 'Z'){
12             TranseStr[n][k] = map[str[j] - 'A'];
13             continue;
14         }
15         TranseStr[n][k] = str[j];
16     }
17     TranseStr[n][k] = '\0';
18 }

 

posted @ 2012-08-09 23:22  bakari  阅读(504)  评论(0编辑  收藏  举报