1. 程式人生 > >LeetCode(657)Judge Route Circle

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

分析

題意判斷機器人能否按照給定的行走方向回到原點。

前進共有4個選擇:U,D,L,R;

只需求出每個方向的前進步數,判斷U==D,且L==R即可。

程式碼

class Solution {
     public boolean judgeCircle(String moves) {
        if (moves.isEmpty()) {
            return true;
        }
        int countU = 0, countD = 0, countL = 0, countR = 0, len = moves.length();
        for (int i = 0; i < len; ++i) {
            char c = moves.charAt(i);
            switch (c) {
                case 'U':
                    ++countU;
                    break;
                case 'D':
                    ++countD;
                    break;
                case 'L':
                    ++countL;
                    break;
                case 'R':
                    ++countR;
                    break;
                default:
                    return false;
            }
        }
        return countD == countU && countL == countR;
    }
}