这道题的题意就是如果遇到相同的号码就输出,这样用 STL 中的 map 加上 string 可以写的很简单,但是结果就不是很好了。
好囧的时间,2000ms 的题 1954ms 卡过,在代码中的 map 可以用离散化 hash 代替,可以大大地优化代码。
我的代码思路就是读取字符串,hash,然后对应的映射加 1,最后统计大于等于 2 的全部输出即可,cnt 计数器,当 cnt 等于 0 的时候输出 No duplicates。之前漏了这个,WA 了两次。。。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
   | #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <map> #include <string>
  using namespace std;
  const char hash[100] = "22233344455566677778889999";
  int main() {   int n, cnt, len;   string ret;   char str[100];   map<string, int> mp;   scanf("%d", &n);   while (n--) {     scanf("%s", str);     cnt = 0;     ret = "";     len = strlen(str);     for (int i = 0; i < len; i++) {       if (str[i] >= '0' && str[i] <= '9') {         ret += str[i];         cnt++;         if (cnt == 3) ret += '-';       } else if (str[i] >= 'A' && str[i] < 'Z' && str[i] != 'Q') {         ret += hash[str[i] - 'A'];         cnt++;         if (cnt == 3) ret += '-';       }       if (cnt == 7) break;     }     mp[ret]++;   }   cnt = 0;   map<string, int>::iterator it;   for (it = mp.begin(); it != mp.end(); it++) {     if ((*it).second > 1) {       printf("%s %d\n", (*it).first.c_str(), (*it).second);       cnt++;     }   }   if (cnt == 0) printf("No duplicates.\n");   return 0; }
   |