#google面试题目13#输出对应字符的操作序列

Given the English alphabet, 'a' through 'z' (lowercase), and an imaginary onscreen keyboard 
with the letters laid out in 6 rows and 5 columns:

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

Using a remote control - (up - 'u', down 'd', left 'l', right 'r' and enter '!'), write a 
function that given a word will produce the sequence of key presses required to type out 
the word on the onscreen keyboard. The function should return the sequence string. 
例如"hello",就输出 d r r ! u r r ! d d l l l ! ! r r r !


分析:

If we observe the 2D matrix[6][5], we have integer values as (intVal) : 
a -> 0 
b -> 1 
e -> 4 
f -> 5 



z -> 25 
===================== 
Map these 1D values to 2D index values. 

Let [ _i ] [ _j ] be current position of cursor on matrix. 

Let i be a row_no and j be col_no. 
ROW = 6; 
COL = 5; 

for any alphabet 'input', find [i][j] like this 
i = intVal(input) / COL; 
j = intVal(input) % COL; 

now first move (i - _i) horizontal steps, then move (j - _j) vertical steps. This can be printed also. 
After reaching to [i][j], print '!' (OK button), then update values of [ _i ] [ _j ] equal to [i][j].


#include <cstdio>

void PrintKeySequence(const char* word, char* sequence)
{
    int row = 0;
    int col = 0;
    int ch,dst_row,dst_col,row_diff,col_diff,i,j,k;
    for(i = 0,j = 0; word[i]; i++)
    {
        ch = word[i] - 'a';
        dst_row = ch / 5;
        dst_col = ch % 5;

        row_diff = row - dst_row;
        col_diff = col - dst_col;
        if (row_diff > 0)
            for(k = 0; k < row_diff; k++)
                sequence[j++] = 'u';
        else
            for(k = 0; k < (0 - row_diff); k++)
                sequence[j++] = 'd';

        if (col_diff > 0)
            for(k = 0; k < col_diff; k++)
                sequence[j++] = 'l';
        else
            for(k = 0; k < (0 - col_diff); k++)
                sequence[j++] = 'r';

        sequence[j++] = '!';
        row = dst_row;
        col = dst_col;
    }
    sequence[j] = '\0';
}

int main()
{
    char word[] = "hello";
    char* seq = new char[100];
    PrintKeySequence(word, seq);
    for(int i = 0; seq[i]; i++)
    {
        printf("%c ", seq[i]);
    }
    printf("\n");
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值