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
相关推荐
笔触狂放27 分钟前
第3章 抓取静态网页数据
爬虫·python
海兰27 分钟前
【 Python 量化交易】开篇
开发语言·python·信息可视化·量化交易
pt104338 分钟前
网络自动化Python课程:Netconf与Restconf及Cisco自动化配置实验
网络·python·自动化
slacker-kian1 小时前
[笔记]-什么是相似性搜索?
python·ai·向量·相似性搜索·点积·l2 距离·余弦相似度和距离
阿童木写作1 小时前
跨境电商图片翻译工具,批量翻译视频字幕还免费
python·音视频
sukioe1 小时前
城智连响:基于 LangGraph 与四库分层架构的城市公共设施智能报修与派单系统
人工智能·python·ai·架构·langchain
卷无止境2 小时前
Coding Agent 里的上下文 Compact,到底在压缩什么
后端·python
Patrick在香港2 小时前
Claude Prompt Caching 实测账单:第一轮贵 25%,从第二轮开始省 86%
python·prompt·claude·成本优化·prompt缓存·anthropic api
新时代牛马2 小时前
字符设备注册:从cdev_add 到chrdev_open 的 VFS路径
python
life1692 小时前
python requests采集同花顺F10、龙虎榜数据
python·同花顺·龙虎榜