Tcdian / keep

今天不想做,所以才去做。
MIT License
5 stars 1 forks source link

657. Robot Return to Origin #317

Open Tcdian opened 3 years ago

Tcdian commented 3 years ago

657. Robot Return to Origin

在二维平面上,有一个机器人从原点 (0, 0) 开始。给出它的移动顺序,判断这个机器人在完成移动后是否在 (0, 0) 处结束。

移动顺序由字符串表示。字符 move[i] 表示其第 i 次移动。机器人的有效动作有 R(右),L(左),U(上)和 D(下)。如果机器人在完成所有动作后返回原点,则返回 true。否则,返回 false。

注意:机器人“面朝”的方向无关紧要。 “R” 将始终使机器人向右移动一次,“L” 将始终向左移动等。此外,假设每次移动机器人的移动幅度相同。

Example 1

Input: "UD"
Output: true 
Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.

Example 2

Input: "LL"
Output: false
Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves.
Tcdian commented 3 years ago

Solution

/**
 * @param {string} moves
 * @return {boolean}
 */
var judgeCircle = function(moves) {
    const counts = new Map([['U', 0], ['D', 0], ['R', 0], ['L', 0]]);
    for (let i = 0; i < moves.length; i++) {
        counts.set(moves[i], counts.get(moves[i]) + 1);
    }
    return counts.get('U') === counts.get('D') && counts.get('R') === counts.get('L');
};
function judgeCircle(moves: string): boolean {
    const counts = new Map([['U', 0], ['D', 0], ['R', 0], ['L', 0]]);
    for (let i = 0; i < moves.length; i++) {
        counts.set(moves[i], counts.get(moves[i])! + 1);
    }
    return counts.get('U') === counts.get('D') && counts.get('R') === counts.get('L');
};