博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode C++ 657. Robot Return to Origin【字符串】简单
阅读量:2007 次
发布时间:2019-04-28

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

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: falseExplanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves.

题意:二维平面上的一个机器人从原点 (0, 0) 开始。给出它的移动顺序,判断这个机器人在完成移动后是否在 (0, 0) 处结束。注意:机器人“面朝”的方向无关紧要。


思路:简单题目,用坐标进行模拟。代码如下:

class Solution {
public: bool judgeCircle(string moves) {
int x = 0, y = 0; for (char c : moves) {
switch (c) {
case 'R' : ++x; break; case 'L' : --x; break; case 'U' : ++y; break; case 'D' : --y; break; } } return !x && !y; }};

思路2:计算 U, D, L, R 的出现次数,如果 U = D, L = R 就会回到原点。代码如下:

class Solution {
public: bool judgeCircle(string moves) {
int u, d, l, r; u = d = l = r = 0; for (char c : moves) {
switch (c) {
case 'R' : ++r; break; case 'L' : ++l; break; case 'U' : ++u; break; case 'D' : ++d; break; } } return u == d && l == r; }};

转载地址:http://hxotf.baihongyu.com/

你可能感兴趣的文章
【软件-Doxgen】工具:程序代码生成xml文档(doxgen)
查看>>
【框架-MFC】CMFCPropertyGridCtrl(chenlu1):属性值改变事件的触发与处理
查看>>
【框架-MFC】CView(chenlu1):MFC在CView的派生类中实现打印和打印预览
查看>>
【框架-MFC】CMFCMenuBar 菜单按钮的图标添加
查看>>
【语言-c#】C# 注释详细介绍说明
查看>>
MySQL 内存模型
查看>>
express 解析post方式下的json参数
查看>>
node.js 实现一个简单的登录拦截器
查看>>
c++抽象类、纯虚函数以及巧用纯虚析构函数实现接口类【转】
查看>>
Caffe 安装错误记录及解决办法【转】
查看>>
Android用类继承Application的全局变量使用注意
查看>>
排序算法之冒泡排序
查看>>
排序算法之希尔排序
查看>>
pyqt5之俄罗斯方块
查看>>
算法排序之桶排序
查看>>
lambda表达式初探
查看>>
C++ Template类模板的特化(3.3节, 3.4节)
查看>>
第05章 函数
查看>>
第08章 输入和输出
查看>>
第11章 案例研究: 文本统计
查看>>