题解 | #手机键盘#
手机键盘
https://www.nowcoder.com/practice/20082c12f1ec43b29cd27c805cd476cd
#include<iostream>
#include<string>
using namespace std;
//预处理
//由于每个按键上字母的数量不相同
//因此每个字母需要的按键次数很难直接通过数学公式计算
//可以用预处理策略,先将每个字母的按键次数记录在一个数组中
//每遇到一个字母,直接访问数组便可得到该字母的按键次数。
// 1 || 2 abc || 3 def
// 4 ghi || 5 jkl || 6 mno
// 7 pqrs || 8 tuv || 9 wxyz
//顺便学习一下map容器
//想不到更好办法的情况下可以这样存每个字母所在位置,用以判断是否是同一组
//map<char,int> keyGroup={
// {'a',2},{'b',2},{'c',2},
// {'d',3},{'e',3},{'f',3},
// ...
//}
//更好的办法只需要存每个字母需要按几次键就可以
//如果字母ASCII码差异等于按键次数差异则说明字母在同一个按钮
//map<char,int> keyTimes={
//
//}
//map查找虽好,但是输入起来真的好麻烦,不如用数组
int Times[26] = {1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 1, 2, 3, 4};
//对应的索引为key-'a'
const int wait = 2;
int main() {
string str;
int length;
int count;
while (cin >> str) {
length = str.length();
count = 0;
count += Times[str[0] - 'a'];
for (int i = 1; i < length; i++) {
//要按的次数分为两部分
//1 自己要按的次数
//2 如果和前面相同位置相同,多等两分钟
count += Times[str[i] - 'a'];
if (str[i] - str[i - 1] == Times[str[i] - 'a'] - Times[str[i - 1] - 'a']) {
count += wait;
}
}
printf("%d\n", count);
}
}
预处理找到好方法可以少敲不少键盘
查看9道真题和解析