LeetCode 657. Judge Route Circle (Easy)

来源:互联网 发布:网络推广维护 编辑:程序博客网 时间:2024/06/18 16:20

题目描述:

Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place.
The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle.

Example 1:

Input: "UD"Output: true

Example 2:

Input: "LL"Output: false

大意:就是一个机器人在原点,会做出四种动作:上、下、左、右移动,给出一个动作序列,问经过这个序列后机器人是否返回原点。

思路:这道题没什么可说的,毕竟是easy难度。就是看这个序列内的动作是否会抵消掉(左右抵消,上下抵消),如果最后上下左右都各自抵消掉那就是在原点,因此只要读取序列,计算序列中上下左右的次数,如果上下次数相同(抵消),左右次数相同(抵消),那么机器人就在原点。

c++代码:

class Solution {public:    bool judgeCircle(string moves) {        int u = 0, d = 0, l = 0, r = 0;        for (int i = 0; i < moves.size(); i++)        {            if (moves[i] == 'U')                u++;            else if (moves[i] == 'D')                d++;            else if (moves[i] == 'L')                l++;            else                r++;        }        if (d == u && l == r)            return true;        return false;    }};

复杂度:就是扫描字符串,时间复杂度O(n),n为序列长度。