【LetMeFly】2833.距离原点最远的点:计数
力扣题目链接:https://leetcode.cn/problems/furthest-point-from-origin/
给你一个长度为 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皆为固定,凡是其他皆自由。
因此两个变量统计:
L和R作用下距离起点的diff;- 有多少自由移动的步数。
如果diff大于0(在起点之右),则自由步数全部向右移动;否则全部向左移动就好了。
此外,也可以不判断diff是否大于零,直接返回 a b s ( d i f f ) + f l e x abs(diff)+flex abs(diff)+flex就好了。
- 时间复杂度 O ( l e n ( m o v e s ) ) O(len(moves)) O(len(moves))
- 空间复杂度 O ( 1 ) O(1) O(1)
AC代码
C++
cpp
/*
* @LastEditTime: 2026-04-24 21:00:44
*/
class Solution {
public:
int furthestDistanceFromOrigin(string moves) {
int flex = 0, diff = 0;
for (char c : moves) {
switch (c)
{
case 'L':
diff--;
break;
case 'R':
diff++;
break;
default:
flex++;
}
}
return diff > 0 ? diff + flex : flex - diff;
}
};
Python
python
'''
LastEditTime: 2026-04-24 21:02:38
'''
class Solution:
def furthestDistanceFromOrigin(self, moves: str) -> int:
flex = diff = 0
for c in moves:
if c == 'L':
diff -= 1
elif c == 'R':
diff += 1
else:
flex += 1
return flex + diff if diff > 0 else flex - diff
Java
java
/*
* @LastEditTime: 2026-04-24 21:07:01
*/
// java14+
class Solution {
public int furthestDistanceFromOrigin(String moves) {
int flex = 0, diff = 0;
for (int i = 0; i < moves.length(); i++) {
switch (moves.charAt(i)) {
case 'L' -> diff--;
case 'R' -> diff++;
default -> flex++;
}
}
return diff > 0 ? flex + diff : flex - diff;
}
}
Go
go
/*
* @LastEditTime: 2026-04-24 21:25:20
*/
package main
func furthestDistanceFromOrigin(moves string) int {
flex, diff := 0, 0
for _, c := range moves {
switch byte(c) {
case 'L':
diff--
case 'R':
diff++
default:
flex++
}
}
if diff > 0 {
return diff + flex
}
return flex - diff
}
Rust - abs
rust
/*
* @LastEditTime: 2026-04-24 23:09:59
*/
impl Solution {
pub fn furthest_distance_from_origin(moves: String) -> i32 {
let mut diff: i32 = 0;
let mut flex: i32 = 0;
for c in moves.chars() {
match c {
'L' => diff -= 1,
'R' => diff += 1,
_ => flex += 1,
}
}
diff.abs() + flex
}
}
Rust - if-else
rust
/*
* @LastEditTime: 2026-04-24 23:07:48
*/
impl Solution {
pub fn furthest_distance_from_origin(moves: String) -> i32 {
let mut diff = 0;
let mut flex = 0;
for c in moves.chars() {
match c {
'L' => diff -= 1,
'R' => diff += 1,
_ => flex += 1,
}
}
if diff > 0 {
diff + flex
} else {
flex - diff
}
}
}
同步发文于CSDN和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~
千篇源码题解已开源