LeetCode 题解工作台
距离原点最远的点
给你一个长度为 n 的字符串 moves ,该字符串仅由字符 'L' 、 'R' 和 '_' 组成。字符串表示你在一条原点为 0 的数轴上的若干次移动。 你的初始位置就在原点( 0 ),第 i 次移动过程中,你可以根据对应字符选择移动方向: 如果 moves[i] = 'L' 或 moves[i] …
2
题型
6
代码语言
3
相关题
当前训练重点
简单 · string·结合·计数
答案摘要
遇到字符 `'_'` 时,我们可以选择向左或向右移动,而题目需要我们求出离原点最远的点,因此,我们可以先进行一次遍历,贪心地把所有的 `'_'` 都移到左边,求出此时离原点最远的点,再进行一次遍历,贪心地把所有的 `'_'` 都移到右边,求出此时离原点最远的点,最后取两次遍历中的最大值即可。 进一步地,我们只需要统计出字符串中 `'L'`、`'R'` 的个数之差,再加上 `'_'` 的个数即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 string·结合·计数 题型思路
题目描述
给你一个长度为 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 <= 50moves仅由字符'L'、'R'和'_'组成
解题思路
方法一:贪心
遇到字符 '_' 时,我们可以选择向左或向右移动,而题目需要我们求出离原点最远的点,因此,我们可以先进行一次遍历,贪心地把所有的 '_' 都移到左边,求出此时离原点最远的点,再进行一次遍历,贪心地把所有的 '_' 都移到右边,求出此时离原点最远的点,最后取两次遍历中的最大值即可。
进一步地,我们只需要统计出字符串中 'L'、'R' 的个数之差,再加上 '_' 的个数即可。
时间复杂度 ,其中 为字符串的长度。空间复杂度 。
class Solution:
def furthestDistanceFromOrigin(self, moves: str) -> int:
return abs(moves.count("L") - moves.count("R")) + moves.count("_")
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) for a single pass counting moves, and space complexity is O(1) since only counts are stored, not the full string transformations. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Expect candidates to recognize '_' as a flexible move affecting counting.
- question_mark
Look for a clear approach to replace all underscores with the same direction for maximum effect.
- question_mark
Candidates may fail to consider negative positions; absolute distance matters.
常见陷阱
外企场景- error
Replacing underscores inconsistently reduces maximum distance.
- error
Counting only 'R' moves or only 'L' moves instead of using absolute difference.
- error
Attempting brute-force string generation instead of counting strategy.
进阶变体
外企场景- arrow_right_alt
Return the actual sequence of moves that produces the furthest distance instead of just the distance.
- arrow_right_alt
Handle a 2D grid instead of a 1D number line with 'U', 'D', 'L', 'R' and '_' characters.
- arrow_right_alt
Limit the number of underscores that can be replaced to a fixed value k instead of all.