题解 | #手机键盘#
手机键盘
https://www.nowcoder.com/practice/20082c12f1ec43b29cd27c805cd476cd
#include<bits/stdc++.h>
using namespace std;
int calculateTime(string str)
{
//定义字母对应的按键位置{按键,{位置,按键次数}}
unordered_map<char,pair<int,int>> keyboard={
{'a',{1,1}},{'b',{1,2}},{'c',{1,3}},
{'d',{2,1}},{'e',{2,2}},{'f',{2,3}},
{'g',{3,1}},{'h',{3,2}},{'i',{3,3}},
{'j',{4,1}},{'k',{4,2}},{'l',{4,3}},
{'m',{5,1}},{'n',{5,2}},{'o',{5,3}},
{'p',{6,1}},{'q',{6,2}},{'r',{6,3}},{'s',{6,4}},
{'t',{7,1}},{'u',{7,2}},{'v',{7,3}},
{'w',{8,1}},{'x',{8,2}},{'y',{8,3}},{'z',{8,4}}
};
int time=0;//记录按键次数
int prev_position=0;//记录上一个按键
for(char c:str)
{
int position=keyboard[c].first;//记录当前字母在哪个键上
if(position==prev_position)//如果跟上一个字母在同一个键上,则需要等待
{
time+=2;
}
prev_position=keyboard[c].first;//记录当前按键
time+=keyboard[c].second;//加上按键次数
}
return time;
}
int main()
{
string input;
while(cin>>input)
{
cout<<calculateTime(input)<<endl;
}
}
查看9道真题和解析