LeetCode_ 657. Judge Route Circle

题目:
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;
    }
};

你可能感兴趣的:(leetcode,数据结构,算法)