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
相关推荐
明如正午16 分钟前
用 Python 一键把 ASC 文件转成 BLF(基于 python-can)
python·can·blf·asc
y1su34 分钟前
Leetcode 二分模板
java·数据结构·算法·leetcode·排序算法
leisoo80971 小时前
融资融券数据怎么查两融指标含义与杠杆观察方法 IG50免费开源股票数据API接口
开发语言·jvm·数据库·python·json
Patrick在香港1 小时前
同一份脚本,mac 正常 Windows 乱码:open() 默认编码实测(附 3.15 终局)
utf-8·windows·python·macos·跨平台·编码·标准库
勿信日志1 小时前
Playwright 元素定位:一个 width>50 过滤器把 42px 的输入框删掉了
python
larance2 小时前
[菜鸟教程] 机器学习教程十课-Python 机器学习应用
人工智能·python·机器学习
栖凤2 小时前
Java 的 try-catch 在 Agent 里失效了,我用了 5 个模式才兜住
java·前端·python
Pniubi2 小时前
力扣55跳跃游戏(贪心)
算法·leetcode·游戏
Yyyyyy~2 小时前
【python】函数
python
金銀銅鐵2 小时前
[Java] 借助GUI展示class文件的版本号
后端·python·ai编程