LeetCode_ 657. Judge Route Circle

3 篇文章 0 订阅
2 篇文章 0 订阅

题目:
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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值