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 movesi 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
相关推荐
fanruitian6 分钟前
python 机器学习 ML LinearRegression KNN KMeans
python·机器学习·kmeans
鱼宵12 分钟前
取集合第一个元素,Java 为什么要写三种写法?
java·windows·python·java21
卷无止境21 分钟前
给AI装上一双眼睛:快速构建代码验证器的思路与落地方案
后端·python
维克兜率天40 分钟前
【维克】指数调整:哪些股票会被“强制买入“?
人工智能·python·算法
come112341 小时前
Codex 下不同场景 模式选择
python
神也畏惧菠萝1 小时前
Day08 Python流程控制从入门到上瘾:if/match/while/for四件套,从B站登录一路打到猜数字游戏
python·算法·数据存储·for·while·if·ifelse
言乐62 小时前
通过 3D 动画直观演示球形瓶内可滑动半圆机构在倾倒时防粘盖、回正时刮膏体的运动学过程
python·3d·django·virtualenv·pygame
quantdash_cc2 小时前
ETF 行情数据清洗实战:字段语义拆解、标的池整理与五个校验清单
python·数据分析·pandas·量化交易·股票数据·quantdash
小熊恋旧2 小时前
Python 面向对象编程:方法、属性、继承与多态详解
开发语言·python
威哥爱编程3 小时前
Python 智能体开发实战 05:一问教材内容它就编?先把答案从你自己的资料里检索出来
python·agent