输入
bob
www
输出
7
7
【提交地址】
题目分析
九宫格键盘如图所示:
注意,题目中有两个对应关系需要注意:
- 第一,字母与按键次数的对应
- 第二,字母与按键的对应,如果连续两次是不同的按键则不需要等待,如果是相同的按键,需要等待两个时间
显然,需要使用map结构表示这种对应关系。
代码
#include <cstdio>
#include <string>
#include <map>
using namespace std;
int main() {map<char, int> inputTime = {{'a',1},{'b',2},{'c',3},{'d',1},{'e',2},{'f',3},{'g',1},{'h',2},{'i',3},{'j',1},{'k',2},{'l',3},{'m',1},{'n',2},{'o',3},{'p',1},{'q',2},{'r',3},{'s',4},{'t',1},{'u',2},{'v',3},{'w',1},{'x',2},{'y',3},{'z',4}};map<char, int> keyMap{{'a',2},{'b',2},{'c',2},{'d',3},{'e',3},{'f',3},{'g',4},{'h',4},{'i',4},{'j',5},{'k',5},{'l',5},{'m',6},{'n',6},{'o',6},{'p',7},{'q',7},{'r',7},{'s',7},{'t',8},{'u',8},{'v',8},{'w',9},{'x',9},{'y',9},{'z',9}};char str[101];while(scanf("%s",str) != EOF){int lastInput = 1;//初始时置为与其他按键都不同的按键int totalTime = 0;//总的时间计时for (int i = 0; str[i]!='\0'; ++i) {//遍历c风格的字符串if (lastInput == keyMap[str[i]]){//判断是否要等待totalTime+=2;}totalTime += inputTime[str[i]];//输入本字符所要的时间lastInput = keyMap[str[i]];//记录本次按下的按键}printf("%d\n",totalTime);}return 0;
}