题目如下:

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

Here, board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"], as shown in the diagram below.

We may make the following moves:

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

(Here, the only positions that exist on the board are positions with letters on them.)

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.

解题思路:本题难度不大,把整个表格抽象成一个坐标轴,例如a的坐标是(0,0),l的坐标是(2,1),那么从a到l的路径就是要左右方向上移动一次(l的x坐标减去a的x坐标),上下的方向上移动两次(l的坐标减去a的y坐标)。这里有一点需要注意的的是起始或者终止的字符是z,因为不管是从z出发还是到达z,一定只能从经过u到达,而不能经由z的左边。

代码如下:

class Solution(object):
def alphabetBoardPath(self, target):
"""
:type target: str
:rtype: str
"""
board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"]
dic = {}
for i in range(len(board)):
for j in range(len(board[i])):
dic[board[i][j]] = (i,j)
x,y = 0,0
res = ''
for i in target:
x1,y1 = dic[i]
#
if i == 'z':
v = y - y1
if v > 0:
res += 'L' * v
else:
res += 'R' * (-v)
v = x - x1
if v > 0:
res += 'U' * v
else:
res += 'D' * (-v)
else:
v = x - x1
if v > 0:
res += 'U' * v
else:
res += 'D' * (-v)
v = y - y1
if v > 0:
res += 'L'*v
else:
res += 'R' * (-v)
res += '!'
x,y = x1,y1
return res

最新文章

  1. 【源码】Word转PDF V1.0.1 小软件,供新手参考
  2. AX7: Quick and easy debugging
  3. Delphi 自带的那个 Hand 光标很难看?没关系,一行代码解决问题:
  4. Java super与this用法解析
  5. 201521123083《Java程序设计》第二周学习总结
  6. 数据结构与算法 —— 链表linked list(05)
  7. Linux进程-命令行参数和环境列表
  8. 为什么text的值改变后onchange没有反应?
  9. servlet 会话技术
  10. 遍历HTML DOM 树
  11. 【linux】ftp使用端口转发问题
  12. 下载Crypto,CyCrypto,PyCryptodome 报错问题
  13. socket并发聊天
  14. django_rq无法监听两个队列问题
  15. C# 实例化类的执行顺序
  16. HDU 1176 排列2 全排列
  17. Factroy 简单工厂
  18. 【zend studio】如何添加已存在的git项目
  19. HDUOJ -----免费馅饼
  20. 创建基于 AFS 的 Docker 容器卷

热门文章

  1. windows的VMWare下NAT共享无线方式上网的配置
  2. Linux 系统安装 python
  3. kettle入门大数据管理工具
  4. 20191127 Spring Boot官方文档学习(6-8)
  5. 使用screen管理后台程序
  6. linux文件属性软链接
  7. [转帖] 百度百科 sino
  8. 网站私有CA证书制作
  9. window-tree命令
  10. 【React -- 9/100】 抽离顶部导航栏 - [组件复用]