C 657. Can the robot return to the origin

On a two-dimensional plane, there is a robot starting from the origin (0, 0). Given its movement sequence, determine whether the robot ends at (0, 0) after completing the movement.

The order of movement is represented by a character string. The character move [i] indicates its i-th move. The effective actions of the robot are R (right), L (left), U (upper) and D (lower). If the robot returns to the origin after completing all actions, it returns true. Otherwise, return false.

Note: The direction of the "face" of the robot does not matter. "R" will always move the robot to the right once, "L" will always move to the left, etc. In addition, it is assumed that the movement amplitude of the robot is the same every time.

 

Example 1:

Input: "UD"
Output: true
Explanation: The robot moves up once and then down once. All movements have the same amplitude, so it eventually returns to the point where it started. Therefore, we return true.
Example 2:

Input: "LL"
Output: false
Explanation: The robot moves to the left twice. It is ultimately located to the left of the origin, with two "moves" away from the origin. We return false because it did not return to the origin at the end of the move.

Link: https://leetcode-cn.com/problems/robot-return-to-origin
Seeing this letter, I want to use hash _ (: з) ∠) _, in fact, this question is a little simple

bool judgeCircle(char * s)//U D L R 4中命令
{
    int arr[26]={0};
    int i,len=strlen(s);
    for(i=0;i<len;i++)
    {
        arr[s[i]-'A']++;
    }
    if(arr['U'-'A'] == arr['D'-'A']&&arr['L'-'A']==arr['R'-'A'])
    {
        return true ;
    }else  return false ;

}

Solution 2: Use switch for other methods

bool judgeCircle(char * moves){
    int r = 0,u = 0;
    for(int i = 0;moves[i] != '\0';i++){
        switch(moves[i]){
            case 'R':
            r++;break;
            case 'L':
            r--;break;
            case 'U':
            u++;break;
            case 'D':
            u--;break;
        }
    }
    if(r == 0 && u == 0)
        return true;
    else
        return false;
}
链接:https://leetcode-cn.com/problems/robot-return-to-origin/solution/switchshi-yong-ifshi-xian-de-hua-nei-cun-xiao-hao-/

 

Guess you like

Origin www.cnblogs.com/cocobear9/p/12735207.html