难度:简单
给你一个长度为
n
的字符串moves
,该字符串仅由字符'L'
、'R'
和'_'
组成。字符串表示你在一条原点为0
的数轴上的若干次移动。你的初始位置就在原点(
0
),第i
次移动过程中,你可以根据对应字符选择移动方向:
- 如果
moves[i] = 'L'
或moves[i] = '_'
,可以选择向左移动一个单位距离- 如果
moves[i] = 'R'
或moves[i] = '_'
,可以选择向右移动一个单位距离移动
n
次之后,请你找出可以到达的距离原点 最远 的点,并返回 从原点到这一点的距离 。示例 1:
输入:moves = "L_RL__R" 输出:3 解释:可以到达的距离原点 0 最远的点是 -3 ,移动的序列为 "LLRLLLR" 。示例 2:
输入:moves = "_R__LL_" 输出:5 解释:可以到达的距离原点 0 最远的点是 -5 ,移动的序列为 "LRLLLLL" 。示例 3:
输入:moves = "_______" 输出:7 解释:可以到达的距离原点 0 最远的点是 7 ,移动的序列为 "RRRRRRR" 。提示:
1 <= moves.length == n <= 50
moves
仅由字符'L'
、'R'
和'_'
组成题解:
class Solution: def furthestDistanceFromOrigin(self, moves: str) -> int: count_r = moves.count('R') count_l = moves.count('L') if count_r == count_l == 0: return moves.count('_') else: moves2 = moves r_moves = moves.replace("_","L") r_moves2 = moves2.replace("_","R") res1 = 0 res2 = 0 for i in r_moves: if i == 'L': res1 -= 1 else: res1 += 1 for j in r_moves2: if j == 'L': res2 -= 1 else: res2 += 1 return max(abs(res1),abs(res2))
leetcode:2833. 距离原点最远的点(python3解法)
最新推荐文章于 2024-07-17 14:51:05 发布