zoukankan      html  css  js  c++  java
  • Robot Return to Origin

    There is a robot starting at 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.

    The move sequence is represented by a string, and the character moves[i] represents its ith move. Valid moves are R (right), L (left), U (up), and D (down). If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false.

    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.

    Example 1:

    Input: "UD"
    Output: true 
    Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin
    where it started. Therefore, we return true.

    Example 2:

    Input: "LL"
    Output: false
    Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because i

    Python3

     1  1 class Solution:
     2  2     def judgeCircle(self, moves):
     3  3         """
     4  4         :type moves: str
     5  5         :rtype: bool
     6  6         """
     7  7         x = 0
     8  8         y = 0
     9  9         for s in moves:
    10 10             if s == 'U':
    11 11                 y += 1
    12 12             elif s == 'D':
    13 13                 y -= 1
    14 14             elif s == 'R':
    15 15                 x += 1
    16 16             elif s == 'L':
    17 17                 x -= 1
    18 18         if (x, y) == (0, 0):
    19 19             return True
    20 20         else:
    21 21             return False
  • 相关阅读:
    FFmpeg(二) 解封装相关函数理解
    Android NDK(一) ndk-build构建工具进行NDK开发
    Android NDK(二) CMake构建工具进行NDK开发
    C++学习笔记二、头文件与源文件
    C++学习笔记一
    JNA的步骤、简单实例以及资料整理
    Java异常总结
    UML-类图
    排序六:希尔排序
    排序四:归并排序--分治法
  • 原文地址:https://www.cnblogs.com/locke-hu/p/9628107.html
Copyright © 2011-2022 走看看