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
相关推荐
yuanpan19 小时前
Python Pygame 入门教程:从零学会创建窗口、绘图和游戏交互
python·游戏·pygame
2401_8714928519 小时前
如何在 React Router v6 中正确配置多路由组件显示
jvm·数据库·python
神仙别闹20 小时前
基于Python(Django)+MySQL 实现(Web)SQL智能检测系统的设计与实现
python·mysql·django
甄心爱学习20 小时前
【项目实训】法律文书智能摘要系统4
python·github·个人开发
huzhongqiang20 小时前
Playwright理解与封装
python
zhangchaoxies20 小时前
MySQL触发器能否监控特定用户操作_结合审计功能实现分析
jvm·数据库·python
qq_4135020221 小时前
如何解决ORA-12518监听程序无法分配进程_内存耗尽与PGA溢出
jvm·数据库·python
6Hzlia21 小时前
【Hot 100 刷题计划】 LeetCode 141. 环形链表 | C++ 哈希表直觉解法
c++·leetcode·链表
zhangrelay21 小时前
三分钟云课实践速通--大学物理--python 版
linux·开发语言·python·学习·ubuntu·lubuntu
djjdjdjdjjdj21 小时前
如何用参数解构在函数入口处直接提取对象属性
jvm·数据库·python