手机键盘

题目1079:手机键盘

题目描述: 按照手机键盘输入字母的方式,计算所花费的时间 如:a,b,c都在“1”键上,输入a只需要按一次,输入c需要连续按三次。 如果连续两个字符不在同一个按键上,则可直接按,如:ad需要按两下,kz需要按6下 如果连续两字符在同一个按键上,则两个按键之间需要等一段时间,如ac,在按了a之后,需要等一会儿才能按c。 现在假设每按一次需要花费一个时间段,等待时间需要花费两个时间段。 现在给出一串字符,需要计算出它所需要花费的时间。


思路:第一个字母时间段是(1+列位置+1);第二个字母需要根据第一个字母来得出时间,即第二个字母如果和第一个字母在同一行,即按第二个字母的时间段为(2+列位置+1),反之不在同一个位置,则其时间段为(1+列位置+1)。然后把每个字母的时间段加起来。 ps:行列从0开始,所以列位置需加1.

代码:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 int distribute[26] = {0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,5,6,6,6,7,7,7,7};
 5 int spend[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};
 6 void main()
 7 {
 8         char str[100];
 9         int i, len, count, key;
10 
11         while(scanf("%s", str) != EOF)
12         {
13                 for(i = 0, len = strlen(str), count = 0; i < len; i ++)
14                 {
15                         key = str[i] - 'a';
16                         count += spend[key];
17                         if(i > 0)
18                         {
19                                 if(distribute[str[i - 1] - 'a'] == distribute[key])
20                                 {
21                                         count += 2;
22                                 }
23                         }
24                 }
25                 printf("%d
", count);
26         }
27 }

我的笨方法:

#include <stdio.h>
#include <cstring>
#include <string>
#include <iostream>
using namespace std;
//是考察二维数组的查找
char s[100];
char ch[8][4]={{'a','b','c'},
            {'d','e','f'},
            {'g','h','i'},
            {'j','k','l'},
            {'m','n','o'},
            {'p','q','r','s'},
            {'t','u','v'},
            {'w','x','y','z'}};
int solve51(string str)
{
    int sum=0;
    int q,i,j;
    int pre_i=-1;
    int len=str.size();
    bool flag=false;
    for (q=0;q<len;++q)
    {
        flag=false;
        for (i=0;i<8;++i)
        {
            if(flag)
                break;
            for (j=0;j<4;++j)
            {
                if(q!=0&&pre_i==i&&ch[i][j]==str[q])
                {
                    sum+=(j+1)+2;
                    flag=true;
                    break;
                }
                if(ch[i][j]==str[q])
                {
                    sum+=(j+1);
                    pre_i=i;
                    flag=true;
                    break;
                }
            }
        }
    }
    return sum;
}
int main()
{
    string str;
    //freopen("a.txt","r",stdin);
    while(cin>>str)
    {
        if(str.empty())
            cout<<"0"<<endl;
        else
            cout<<solve51(str)<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/fightformylife/p/4024013.html