当前位置 : 首页 » 文章分类 :  算法  »  LeetCode.657.Robot Return to Origin 机器人能否返回原点

LeetCode.657.Robot Return to Origin 机器人能否返回原点


题目描述

657 Robot Return to Origin
https://leetcode.com/problems/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 it is not at the origin at the end of its moves.

解题过程

这个题也很简单,只要R和L、U和D能成对的消掉就是能回到起始点,所以思路是一次遍历统计字符串中RLUD的个数,RL个数相等且UD个数相等就是能回到起点。

private static class SolutionV2018 {
    public boolean judgeCircle(String moves) {
        int Lnum = 0, Rnum = 0, Unum = 0, Dnum = 0;
        for (int i = 0; i < moves.length(); i++) {
            switch (moves.charAt(i)) {
                case 'L':
                    Lnum++;
                    break;
                case 'R':
                    Rnum++;
                    break;
                case 'U':
                    Unum++;
                    break;
                case 'D':
                    Dnum++;
                    break;
                default:
                    break;
            }
        }
        if (Lnum == Rnum && Unum == Dnum) {
            return true;
        } else {
            return false;
        }
    }
}

AC后看了几个别人的代码,思路完全一样,都是统计LRUD个数然后判断相等,只不过转为char数组操作就快,直接操作java String类就慢。


GitHub代码

algorithms/leetcode/leetcode/_657_RobotReturnToOrigin.java
https://github.com/masikkk/algorithms/blob/master/leetcode/leetcode/_657_RobotReturnToOrigin.java


上一篇 LeetCode.557.Reverse Words in a String III 反转字符串中的单词 III

下一篇 LeetCode.344.Reverse String 反转字符串

阅读
评论
429
阅读预计2分钟
创建日期 2018-01-04
修改日期 2018-01-11
类别

页面信息

location:
protocol:
host:
hostname:
origin:
pathname:
href:
document:
referrer:
navigator:
platform:
userAgent:

评论