You are given a string moves of length n consisting only of characters
'L', 'R', and '_'. The string represents your movement on a number line starting from the origin 0.
In the ith move, you can choose one of the following directions:
move to the left if moves[i] = 'L' or moves[i] = '_'
move to the right if moves[i] = 'R' or moves[i] = '_'
Return _thedistance from the origin of the furthest point you can get to after _nmoves.
Input: moves ="L_RL__R"Output: 3Explanation: The furthest point we can reach from the origin 0is point -3 through the following sequence of moves "LLRLLLR".
Input: moves ="_R__LL_"Output: 5Explanation: The furthest point we can reach from the origin 0is point -5 through the following sequence of moves "LRLLLLL".
Input: moves ="_______"Output: 7Explanation: The furthest point we can reach from the origin 0is point 7 through the following sequence of moves "RRRRRRR".
Each ‘L’ moves left, each ‘R’ moves right, and each ‘’ can be used as either. To get the furthest distance, use all ‘’ in one direction (either all left or all right), and add to the count of L or R, whichever is larger.
classSolution {
publicintfurthestDistanceFromOrigin(String moves) {
int l = 0, r = 0, u = 0;
for (char c : moves.toCharArray()) {
if (c =='L') l++;
elseif (c =='R') r++;
else u++;
}
return Math.abs(l - r) + u;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funfurthestDistanceFromOrigin(moves: String): Int {
var l = 0; var r = 0; var u = 0for (c in moves) {
when (c) {
'L'-> l++'R'-> r++else-> u++ }
}
return kotlin.math.abs(l - r) + u
}
}
1
2
3
4
5
6
classSolution:
deffurthestDistanceFromOrigin(self, moves: str) -> int:
l = moves.count('L')
r = moves.count('R')
u = moves.count('_')
return abs(l - r) + u
1
2
3
4
5
6
7
8
impl Solution {
pubfnfurthest_distance_from_origin(moves: String) -> i32 {
let l = moves.chars().filter(|&c| c =='L').count() asi32;
let r = moves.chars().filter(|&c| c =='R').count() asi32;
let u = moves.chars().filter(|&c| c =='_').count() asi32;
(l - r).abs() + u
}
}