Track horizontal and vertical displacement while scanning the move string, then test whether both coordinates are zero.
Complexity
O(n) time and O(1) extra space.
Check whether a sequence of unit moves returns a robot to its starting point.
Track horizontal and vertical displacement while scanning the move string, then test whether both coordinates are zero.
O(n) time and O(1) extra space.
package main
func judgeCircle(moves string) bool {
horizontal, vertical := 0, 0
for _, move := range moves {
switch move {
case 'L':
horizontal--
case 'R':
horizontal++
case 'U':
vertical++
case 'D':
vertical--
}
}
return horizontal == 0 && vertical == 0
}
class Solution:
def judgeCircle(self, moves: str) -> bool:
horizontal = vertical = 0
for move in moves:
if move == "L": horizontal -= 1
elif move == "R": horizontal += 1
elif move == "U": vertical += 1
else: vertical -= 1
return horizontal == 0 and vertical == 0
function judgeCircle(moves: string): boolean {
let horizontal = 0;
let vertical = 0;
for (const move of moves) {
if (move === "L") horizontal -= 1;
else if (move === "R") horizontal += 1;
else if (move === "U") vertical += 1;
else vertical -= 1;
}
return horizontal === 0 && vertical === 0;
}