当前位置: 首页 > news >正文

算法刷题打卡第88天:字母板上的路径

字母板上的路径

难度:中等

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

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

请添加图片描述
我们可以按下面的指令规则行动:

  • 如果方格存在,'U' 意味着将我们的位置上移一行;
  • 如果方格存在,'D' 意味着将我们的位置下移一行;
  • 如果方格存在,'L' 意味着将我们的位置左移一列;
  • 如果方格存在,'R' 意味着将我们的位置右移一列;
  • '!' 会把在我们当前位置 (r, c) 的字符 board[r][c] 添加到答案中。
    (注意,字母板上只存在有字母的位置。)

返回指令序列,用最小的行动次数让答案和目标 target 相同。你可以返回任何达成目标的路径。

示例 1:

输入:target = "leet"
输出:"DDR!UURRR!!DDD!"

示例 2:

输入:target = "code"
输出:"RR!DDRR!UUL!R!"

哈希表

思路:

  • 根据字符输入,可以计算出对应的位置
  • 根据位置左右和上下移动即可
  • 需注意,移动到z只能先左右再上下,从z移动出去只能先上下再左右

复杂度分析:

  • 时间复杂度: O(n)O(n)O(n)nnntargettargettarget 长度
  • 空间复杂度: O(c)O(c)O(c)ccc262626
class Solution:def alphabetBoardPath(self, target: str) -> str:word_dicts = dict()board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"]for x, i in enumerate(board):for y, j in enumerate(i):word_dicts[j] = [x, y]now_position = [0, 0]res = ""def lr_move(target_position, now_position, res):if target_position[1] - now_position[1] >= 0:res += 'R' * abs(target_position[1] - now_position[1])else:res += 'L' * abs(target_position[1] - now_position[1])return resdef ud_move(target_position, now_position, res):if target_position[0] - now_position[0] >= 0:res += 'D' * abs(target_position[0] - now_position[0])else:res += 'U' * abs(target_position[0] - now_position[0])return resfor i in target:target_position = word_dicts[i]if i != 'z':res = ud_move(target_position, now_position, res)res = lr_move(target_position, now_position, res)else:              res = lr_move(target_position, now_position, res)res = ud_move(target_position, now_position, res)res += "!"now_position = target_positionreturn res

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/alphabet-board-path

http://www.lryc.cn/news/4496.html

相关文章:

  • UVa The Morning after Halloween 万圣节后的早晨 双向BFS
  • Connext DDS属性配置参考大全(3)
  • Docker-安装Jenkins-使用jenkins发版Java项目
  • spring 中的 Bean 是否线程安全
  • 微电网两阶段鲁棒优化经济调度方法[3]【升级优化版本】(Matlab代码实现)
  • C++入门教程||C++ 数据类型||C++ 变量类型
  • 【visio使用技巧】图片导出pdf时去掉多余空白
  • Rust语言之Option枚举类型
  • 基于TimeQuest时序优化原理和方法
  • LeetCode第332场周赛
  • 2023-2-12刷题情况
  • 拉普拉斯矩阵
  • Top-1错误率、Top-5错误率等常见的模型算法评估指标解析
  • Urho3D 容器类型
  • C语言学习笔记(四): 循环结构程序设计
  • 02 OpenCV图像通道处理
  • 微信小程序图书馆座位预约管理系统
  • 有限元分析学习一
  • android avb2.0 总结
  • 聊天机器人-意图识别类,开源库推荐
  • Java 标识符以及修饰符
  • 封装、继承、Super、重写、多态instanceof类型转换的使用以及个人见解
  • day13_面向对象的三大特征之一(封装)
  • 越界访问数组
  • 软件设计(十)--计算机系统知识
  • 【不知道是啥】浅保存哈
  • 2021 WAIC 世界人工智能大会参会总结
  • ThingsBoard-实现定时任务调度器批量RPC
  • MySQL数据库调优————数据库调优维度及测试数据准备
  • 电子货架标签多种固定方式