Leetcode 657. Robot Return to Origin

Problem

There is a robot starting at the position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves.

You are given a string moves that represents the move sequence of the robot where moves[i] represents its ith move. Valid moves are 'R' (right), 'L' (left), 'U' (up), and 'D' (down).

Return true if the robot returns to the origin after it finishes all of its moves, or false otherwise.

Note: The way that the robot is "facing" is irrelevant. 'R' will always make the robot move to the right once, 'L' will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.

Algorithm

Simulate movement in all four directions (up, down, left, right), and determine whether it returns to the origin.

Code

python3 复制代码
class Solution:
    def judgeCircle(self, moves: str) -> bool:
        x, y = 0, 0
        for c in moves:
            if c == 'R':
                x += 1
            elif c == 'L':
                x -= 1
            elif c == 'U':
                y += 1
            elif c == 'D':
                y -= 1

        return x == 0 and y == 0
相关推荐
_深海凉_2 小时前
LeetCode热题100-环形链表
算法·leetcode·链表
2402_881319302 小时前
跨服务通信兜底机制-Java 回传失败无持久重试队列,报告可能静默丢失。
java·开发语言·python
memcpy02 小时前
LeetCode 904. 水果成篮【不定长滑窗+哈希表】1516
算法·leetcode·散列表
老四啊laosi2 小时前
[双指针] 8. 四数之和
算法·leetcode·四数之和
田梓燊2 小时前
leetcode 41
数据结构·算法·leetcode
_深海凉_3 小时前
LeetCode热题100-三数之和
算法·leetcode·职场和发展
y = xⁿ3 小时前
【LeetCode】双指针合集
算法·leetcode
生信研究猿3 小时前
一个整数转换为二进制
leetcode
凌波粒3 小时前
LeetCode--18.四数之和(双指针法)
数据结构·算法·leetcode