/**
* Problem: LeetCode 657 - Robot Return to Origin
* Difficulty: Easy
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public boolean judgeCircle(String moves) {
int x = 0;
int y = 0;
for (int i = 0; i < moves.length(); i++) {
char move = moves.charAt(i);
if (move == 'U') {
y++;
} else if (move == 'D') {
y--;
} else if (move == 'R') {
x++;
} else if (move == 'L') {
x--;
}
}
return x == 0 && y == 0;
}
}
"""
Problem: LeetCode 657 - Robot Return to Origin
Difficulty: Easy
Language: Python
Author: CodeByTushu
"""
class Solution:
def judgeCircle(self, moves: str) -> bool:
"""
Determines whether the robot returns to the origin (0, 0) after all moves.
Time Complexity: O(N)
Space Complexity: O(1)
"""
x = 0
y = 0
for move in moves:
if move == 'U':
y += 1
elif move == 'D':
y -= 1
elif move == 'R':
x += 1
elif move == 'L':
x -= 1
return x == 0 and y == 0
/**
* Problem: LeetCode 657 - Robot Return to Origin
* Difficulty: Easy
* Language: C++
* Author: CodeByTushu
*/
#include <string>
using namespace std;
class Solution {
public:
bool judgeCircle(string moves) {
int x = 0;
int y = 0;
for (char move : moves) {
if (move == 'U') y++;
else if (move == 'D') y--;
else if (move == 'R') x++;
else if (move == 'L') x--;
}
return x == 0 && y == 0;
}
};
/**
* Problem: LeetCode 657 - Robot Return to Origin
* Difficulty: Easy
* Language: JavaScript
* Author: CodeByTushu
*/
var judgeCircle = function(moves) {
let x = 0;
let y = 0;
for (let i = 0; i < moves.length; i++) {
const move = moves.charAt(i);
if (move === 'U') {
y++;
} else if (move === 'D') {
y--;
} else if (move === 'R') {
x++;
} else if (move === 'L') {
x--;
}
}
return x === 0 && y === 0;
};