LeetCode 答案(Easy)(601-700)

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.
一开始,机器人位于(0,0)。输入一串移动次序命令,判断机器人是否走了一个圈,也就是说它是否回到了原点。

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.
移动顺序是一串字符串。每一步移动命令都是一个字符。有效的移动命令包括 R(向右) ,L(向左),U(向上)以及D(向下)。最终的输出是true或者false,同来表示机器人是否走了一个圈。

Example 1:
Input: "UD"
Output: true
Example 2:
Input: "LL"
Output: false
  • 答案
public class Solution {
    public boolean judgeCircle(String moves) {

        // x轴坐标
        int x = 0;
        // y轴坐标
        int y = 0;
        for (int j = 0, length = moves.length(); j < length; j++) {
            if (moves.charAt(j) == 'R') {
               x++;
            }
            if (moves.charAt(j) == 'L') {
                 x--;
            }
            if (moves.charAt(j) == 'U') {
                 y++;
            }
            if (moves.charAt(j) == 'D') {
                 y--;
            }
        }
       // System.out.println("机器人当前的坐标是:("+x+","+y+")");
        return (x==0&&y==0);


    }
}

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