GuilinDev

Lc0657

05 August 2008

657 Judge Route Cycle

原题概述

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

1
R
(Right),
1
L
(Left),
1
U
(Up) and
1
D
(down). The output should be true or false representing whether the robot makes a circle.

Example 1:

1
2
Input: "UD"
Output: true

Example 2:

1
2
Input: "LL"
Output: false

题意和分析

找是否绕圈,有多少个U就得有多少个D,有多少个L就得有多少个R,跟20 - Valid Parentheses类似,那道题用stack来解,这个题更简单,两个计数器来看最后是否为0就行了。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
    public boolean judgeCircle(String moves) {
        if (moves == null || moves.length() == 0) {
            return true;
        }
        int countH = 0, countV = 0;
        for (int i = 0; i < moves.length(); i++) {
            if (moves.charAt(i) == 'L') countH++;
            if (moves.charAt(i) == 'R') countH--;
            if (moves.charAt(i) == 'U') countV++;
            if (moves.charAt(i) == 'D') countV--;
        }
        return countH == 0 && countV == 0;
    }
}