LeetCode 1138:字母板上的路径(Alphabet Board Path)解法汇总

博客介绍了如何解决LeetCode中的1138题——字母板上的路径问题。通过一系列上下左右移动,找到从起点到目标字符串的最短路径。示例给出了'leet'和'code'两个输入的解题结果,并指出求解关键是确定每个字母相对于前一个字母的位移,同时注意移动顺序的限制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文章目录


更多LeetCode题解

On an alphabet board, we start at position (0, 0), corresponding to character board[0][0].

Here, board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"].

We may make the following moves:

  • 'U' moves our position up one row, if the square exists;
  • 'D' moves our position down one row, if the square exists;
  • 'L' moves our position left one column, if the square exists;
  • 'R' moves our position right one column, if the square exists;
  • '!' adds the character board[r][c] at our current position (r, c) to the answer.

Return a sequence of moves that makes our answer equal to target in the minimum number of moves. You may return any path that does so.

Example 1:

Input: target = “leet”
Output: “DDR!UURRR!!DDD!”

Example 2:

Input: target = “code”
Output: “RR!DDRR!UUL!R!”

Constraints:

  • 1 <= target.length <= 100
  • target consists only of English lowercase letters.

Solution

求得当前字母的位置相对于前一字母的位置的x y位移即可。

要注意的是z这个字母,从它出去只能先上后右,进入它只能先做后下。

class Solution {
public:
    string alphabetBoardPath(string target) {
        string path;
        int x_index = 0;
        int y_index = 0;
        for(int i=0;i<target.size();i++){
            int x_curr_index = (target[i]-'a')/5;
            int y_curr_index = (target[i]-'a')%5;
            if(target[i]=='z'){
                insertYAlphabet(path, y_curr_index-y_index);
                insertXAlphabet(path, x_curr_index-x_index);
            }
            else{
                insertXAlphabet(path, x_curr_index-x_index);
                insertYAlphabet(path, y_curr_index-y_index);
            }
            path.push_back('!');
            x_index = x_curr_index;
            y_index = y_curr_index;
        }
        return path;
    }
    void insertXAlphabet(string &path, int n){
        if(n>=0){
            for(int i=0;i<n;i++){
                path.push_back('D');
            }
        }
        else{
            for(int i=0;i<abs(n);i++){
                path.push_back('U');
            }
        }
    }
    void insertYAlphabet(string &path, int n){
        if(n>=0){
            for(int i=0;i<n;i++){
                path.push_back('R');
            }
        }
        else{
            for(int i=0;i<abs(n);i++){
                path.push_back('L');
            }
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值