题目描述:
题目思路:
本题存在相应键值对对应,所以应该首先考虑使用STL库中map容器,本体采用unordered_map,特性如下:
关联性:通过key去检索value,而不是通过绝对地址(和顺序容器不同)
无序性:使用hash表存储,内部无序
Map : 每个值对应一个键值
键唯一性:不存在两个元素的键一样
动态内存管理:使用内存管理模型来动态管理所需要的内存空间
然后本题的关键就是大小写的转换,以及最后Z字母转换跳回A
第一个问题是大小写的转换:
//转换方法不唯一
for(int i=0;i<len;i++)
{
if(a[i] >= 'a'&&a[i] <= 'z')
a[i] -= 32;
else if(a[i] >= 'A'&&a[i] <= 'Z')
a[i] += 32;
}
第二个问题是对Z转换到A,这里我的处理办法是给字母Z一个单独判断:
if(ch=='Z')
ch=a;
代码如下:
#include<iostream>
#include<string>
#include<unordered_map>
using namespace std;
int main() {
string s;
unordered_map<char, char> map;
map['a'] = '2'; map['b'] = '2'; map['c'] = '2';
map['d'] = '3'; map['e'] = '3'; map['f'] = '3';
map['g'] = '4'; map['h'] = '4'; map['i'] = '4';
map['j'] = '5'; map['k'] = '5'; map['l'] = '5';
map['m'] = '6'; map['n'] = '6'; map['o'] = '6';
map['p'] = '7'; map['q'] = '7'; map['r'] = '7'; map['s'] = '7';
map['t'] = '8'; map['u'] = '8'; map['v'] = '8';
map['w'] = '9'; map['x'] = '9'; map['y'] = '9'; map['z'] = '9';
while (getline(cin, s)) {
int len = s.size();
for (int i = 0; i < len; ++i) {
if (s[i] >= 'A' && s[i] < 'Z') {
s[i] = s[i] - 'A' + 'a' + 1;
continue;
} else if (s[i] == 'Z') {
s[i] = 'a';
continue;
} else if (s[i] >= 'a' && s[i] <= 'z') {
s[i] = map[s[i]];
continue;
}
}
cout << s << endl;
}
return 0;
}