LeetCode - 字母板上的路径

文章讲述了如何使用简单的数学运算和遍历方法,通过计算目标字母在字母板上的行和列位置,以最少的移动(上、下、左、右)找到从起始点到目标字母的路径,提升算法效率。
摘要由CSDN通过智能技术生成

1138. 字母板上的路径

刚看到这道题的时候,我居然想用搜索去做这道题,其实有更优解,用 / + %算会更加的快,只需要遍历一次即可.假如说我们要找n,n是第13个字母,那他就位于 13 / 5 = 2, 13 % 5 = 3.他就位于三行三列(a为0,0),知道了原理,代码就好写了.

class Solution {
public:
    string alphabetBoardPath(string target) {
        string ans;
        int x = 0, y = 0;
        string v, h;
        for (const auto& it : target)
        {
            int nx = (it - 'a') / 5, ny = (it - 'a') % 5;
            
            if (nx > x)
            {
                v = string(abs(nx - x), 'D');
            }
            else 
            {
                v = string(abs(nx - x), 'U');
            }

            if (ny > y)
            {
                h = string(abs(ny - y), 'R');
            }
            else 
            {
                h = string(abs(ny - y), 'L');
            }

            ans += (it != 'z'? v + h : h + v) + '!';
            x = nx, y = ny;
        }
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值