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.

Example 1:

Input: "UD"
Output: true

 

Example 2:

Input: "LL"
Output: false

题意:在(0,0)处有一个机器人,给它一系列动作,判断机器人完成这一系列动作后能否返回原位置。
动作为:R右;L左;U上;D下。移动顺序是由这四个方向字符组成的字符串,输出true或false,表示机器人是否回到原位置。

思路:假定:向右走加1, 向左走减1;向上走加2,向下走减2。
将字符串转成字符数组,定义一个求和变量sum,逐个遍历每个字符,对每个字符根据其对应的数字进行加减,如果遍历完成后,sum为0,说明机器人回到了原位置;否则就没有回到原位置。代码如下:

public boolean judgeCircle(String moves) {
        char[] chars = moves.toCharArray();
        int sum = 0;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == 'R')
                sum += 1;
            else if (chars[i] == 'L')
                sum -= 1;
            else if (chars[i] == 'U')
                sum += 2;
            else if (chars[i] == 'D')
                sum -= 2;
        }
        return sum == 0 ? true : false;
    }
 
原文地址:https://www.cnblogs.com/zeroingToOne/p/7843253.html