[Ruby] leetCode - 1138. Alphabet Board Path
題目 轉自 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"]
, 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!"
大意是
有一個二維字元表格,輸入一字串,將能夠輸入該字串的方法記錄並輸出
往上走為'U'、往下走為’D'、往左走為'L'、往右走為'R'、選擇該字元為’!‘
解題思路
- 找出每個字元的位置
row、column
- 以目前座標,往目標位置移動
- 找到該字元,以
!
做選擇
範例程式碼
Ruby 範例
附上 Ruby 的 online sandbox,有興趣可以把 code 貼進去玩玩看
board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"]
# @param {String} target
# @return {String}
def alphabet_board_path(target)
column_count = 5
current_x, current_y = 0, 0
result = ''
offset = 'a'.ord
for char in target.chars
row = (char.ord - offset) / column_count
column = (char.ord - offset) % column_count
result += 'L' * (current_y - column) if current_y > column
result += 'D' * (row - current_x) if current_x < row
result += 'U' * (current_x - row) if current_x > row
result += 'R' * (column - current_y) if current_y < column
result += '!'
current_x, current_y = row, column
end
return result
end
pp alphabet_board_path('leet')
結果如下
target 為 leet 時
target 為 code 時