657. Judge Route Circle

Problem:

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
Analysis:
skip
Solution:

class Solution {
    public boolean judgeCircle(String moves) {
        int[] pos = new int[2];
        for (char c: moves.toCharArray()) {
            switch(c) {
                case 'U': 
                    pos[0]--; break;
                case 'D':
                    pos[0]++; break;
                case 'L':
                    pos[1]--; break;
                default:
                    pos[1]++; break;
            }
        }
        return pos[0] == 0 && pos[1] == 0;
    }
}

评论

此博客中的热门博文

776. Split BST

663. Equal Tree Partition

532. K-diff Pairs in an Array