LeetCode——1138. 字母板上的路径

文章讨论了LeetCode上的一个问题,即如何从字母板的(0,0)位置出发,找到到达目标字符串每个字符的最短路径。作者提供了两种C++解法,一种未考虑最优路径,另一种优化了路径选择,避免了特殊处理。两种解法的时间复杂度均为O(n×(r+c)),空间复杂度为O(1)。

一、题目

我们从一块字母板上的位置 (0, 0) 出发,该坐标对应的字符为 board[0][0]。

在本题里,字母板为board = [“abcde”, “fghij”, “klmno”, “pqrst”, “uvwxy”, “z”],如下所示。

在这里插入图片描述
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/alphabet-board-path/description/

二、C++解法

我的思路及代码

刚开始没有注意到可以用任何达成目标的最短序列返回,导致我对z进行了特殊处理,写了屎山代码,随便看看吧,简单版本看参考代码

class Solution {
public:
    string alphabetBoardPath(string target) {
        int row = 0;
        int col = 0;
        int currow=0;
        int curcol=0;
        string ans;
        for(int i=0;i<target.size();i++){
            row = (target[i]-'a')/5;
            col = (target[i]-'a')%5;
            row>currow?ans.append(row == 5?(row-currow-1):(row-currow),'D'):ans.append(currow-row,'U');
            col>curcol?ans.append(col-curcol,'R'):ans.append(curcol - col,'L');
            (row == 5&&row!=currow)?ans.append("D!"):ans.append("!");  
            currow = row;
            curcol = col;
        }
        return ans;
    }
};
  • 时间复杂度:时间复杂度: O(n×(r+c)),其中 n 表示给定字符串的长度,r 表示字母板的行数, c 表示字母板的列数。每次移动到新的字符生成移动指令时,需要的时间复杂度为 r+c,一共需要生成指令 n 次,因此时间复杂度为 O(n×(r+c))
  • 空间复杂度:O(1)

官方参考代码

优先走左边和上边可以避开z的问题

class Solution {
public:
    string alphabetBoardPath(string target) {
        int cx = 0, cy = 0;
        string res;
        for (char c : target) {
            int nx = (c - 'a') / 5;
            int ny = (c - 'a') % 5;
            if (nx < cx) {
                res.append(cx - nx, 'U');
            }
            if (ny < cy) {
                res.append(cy - ny, 'L');
            } 
            if (nx > cx) {
                res.append(nx - cx, 'D');
            }
            if (ny > cy) {
                res.append(ny - cy, 'R');
            }  
            res.push_back('!');
            cx = nx;
            cy = ny;
        }
        return res;
    }
};
  • 时间复杂度:时间复杂度: O(n×(r+c)),其中 n 表示给定字符串的长度,r 表示字母板的行数, c 表示字母板的列数。每次移动到新的字符生成移动指令时,需要的时间复杂度为 r+c,一共需要生成指令 n 次,因此时间复杂度为 O(n×(r+c))
  • 空间复杂度:O(1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天地神仙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值