[Leetcode]657. Robot Return to Origin

Easy

There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves.

The move sequence is represented by a string, and the character moves[i] represents its ith move. Valid moves are R (right), L (left), U (up), and D (down). If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false.

Note: The way that the robot is "facing" is irrelevant. "R" will always make the robot move to the right once, "L" will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.

Example 1:

Input: "UD"
Output: true 
Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.

 

Example 2:

The INPUT: "LL" 
the Output: false 
Explanation:. At The Robot Moves left Twice It ends up TWO "Moves" to at The left of at The Origin We return false Because IT IS not AT at The Origin AT at The End of the ITS Moves.. 

Subject to the effect: a mobile robot according to a given instruction string (the moving direction of the robot is not facing the impact caused, namely: the same as a man moves toward the truck) U is moved upward, D is moved downward, L is moved to the left, R is moved rightward.
If the end of the movement of the robot back to the place returns true, otherwise false.

An array can be used to record the movement of the robot with respect to the origin, the end of the movement if the data array is 0 it means that the robot is moved relative to the origin 0, i.e. no movement, returns true, otherwise returns false.
Then the array will have two, one for recording the results and move around, move up and down a record for results.
code show as below:
class Solution {
public:
    bool judgeCircle(string moves) {
        if(moves.size()==0)return true;
        vector<int> step(2,0);
        for(char c: moves){
            if(c=='L'){
                step[0]++;
            }
            else if(c=='R'){
                step[0]--;
            }
            else if(c=='U'){
                step[1]++;
            }
            else if(c=='D'){
                step[1]--;
            }
        }
        if(step[0]==0 && step[1]==0){
            return true;
        }
        else return false;
    }
};

 

Guess you like

Origin www.cnblogs.com/cff2121/p/11421053.html