LeetCode_ 657. Judge Route Circle
阿新 • • 發佈:2018-12-30
題目:
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;
}
};