文章

454

粉丝

0

获赞

1

访问

10.9k

头像
手机键盘 题解(四语言 AC 代码)
P1157 清华大学上机题
发布于 2026年11月
阅读数 35

题意

小写字母在手机键盘上分组(abc 在 1 键、def 在 2 键…),输入按一次算 1 个时间单位;相邻两个字符若在同一键上,中间要等 2 个时间单位。

思路

  • 预处理每个字母对应的键号和它在键上的位置(按 1~3 下)。

  • 遍历字符串:时间累加按下的次数;若当前字母与上一个字母在同一键,额外加 2。

  • 多组数据直到 EOF。

复杂度

时间 O(L),空间 O(1)。

参考代码(C / C++ / Java / Python)

C:

#include <stdio.h>
#include <string.h>
int keyof(int ch){
if(ch>='a'&&ch<='c')return 0;
if(ch<='f')return 1;
if(ch<='i')return 2;
if(ch<='l')return 3;
if(ch<='o')return 4;
if(ch<='s')return 5;
if(ch<='v')return 6;
return 7;}
int posof(int ch){
static const char*t[8]={"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
int k=keyof(ch),i;for(i=0;t[k][i];i++)if(t[k][i]==ch)return i+1;
return 1;}
int main(void){char s[256];
while(scanf("%s",s)==1){int n=(int)strlen(s),i,tot=0;
for(i=0;i<n;i++){tot+=posof(s[i]);
if(i&&keyof(s[i])==keyof(s[i-1]))tot+=2;}
printf("%d\n",tot);}return 0;}

C++:

#include <iostream>
#include <string>
using namespace std;
int keyof(char ch){
if(ch>='a'&&ch<='c')return 0;
i...
登录查看完整内容


登录后发布评论

暂无评论,来抢沙发