LeetCode_ 657. Judge Route Circle

来源:互联网 发布:长虹乐视网络电视报价 编辑:程序博客网 时间:2024/06/10 18:16

题目:
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.

解释:就是有一个机器人,给它一些指令RLUD(左右上下),看它能不能走一个圈回到原点;

思路:我设置了两个变量sum1,sum2,往左走sum1就减1,往右走sum就+1;上下同理;最后看sum1和sum2是不是为零;
当然如果字符串为奇数,直接就不可能了;

ac代码:

var judgeCircle = function(moves) {    var arr = moves.split('');    var len = arr.length;    var sum1 = 0;    var sum2 = 0;    if (len % 2 == 0) {        for (var i = 0; i < len; i++) {            switch (arr[i]) {                case 'L':                    sum1 -= 1;                    break;                case 'R':                    sum1 += 1;                    break;                case 'U':                    sum2 -= 1;                    break;                case 'D':                    sum2 += 1                    break;            }        }    } else {        return false    }    if (sum1 == 0 && sum2 == 0) {        return true    } else {        return false;    }};
原创粉丝点击