博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
10. Robot Return to Origin
阅读量:5231 次
发布时间:2019-06-14

本文共 1662 字,大约阅读时间需要 5 分钟。

Title:

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.

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:

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.

Analysis of Title:

It's easy. But there are some interesting methods.

Test case:

"UD"

Python:

Method one: Go through 4 times.

  return moves.count('L') == moves.count('R') and moves.count('U') == moves.count('D')  

Mehtod two: Gothrough 1 times.

u,d,r,l=1,1,1,1

for i in moves:
  if i=='U':
    u+=1
  elif i=='D':
    d+=1
  elif i=='R':
    r+=1
  else:
    l+=1
  if d==u and r==l:
    return True
  return False

But this method uses too many variables and below this is better.

x, y = 0, 0

for i in moves:
  if i == "U":
    y += 1
  elif i == "D":
    y -= 1
  elif i == "R":
    x += 1
  elif i == "L":
    x -= 1
  if x == 0 and y == 0:
    return True
  else:
    return False

Analysis of Code:

Use less variables.

转载于:https://www.cnblogs.com/sxuer/p/10654218.html

你可能感兴趣的文章
Hive教程(1)
查看>>
第16周总结
查看>>
C#编程时应注意的性能处理
查看>>
Fragment
查看>>
比较安全的获取站点更目录
查看>>
苹果开发者账号那些事儿(二)
查看>>
使用C#交互快速生成代码!
查看>>
UVA11374 Airport Express
查看>>
P1373 小a和uim之大逃离 四维dp,维护差值
查看>>
NOIP2015 运输计划 树上差分+树剖
查看>>
P3950 部落冲突 树链剖分
查看>>
读书_2019年
查看>>
读书汇总贴
查看>>
微信小程序 movable-view组件应用:可拖动悬浮框_返回首页
查看>>
MPT树详解
查看>>
空间分析开源库GEOS
查看>>
RQNOJ八月赛
查看>>
前端各种mate积累
查看>>
jQuery 1.7 发布了
查看>>
Python(软件目录结构规范)
查看>>