Leet - 657

Having fun on Leetcode with C++, Java, Python & GO

Problem 657. Robot Return to Origin

My attempt(s)

Code

C++

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
public:
    bool judgeCircle(string moves) {
       if ((count(moves.begin(), moves.end(), 'U')==count(moves.begin(), moves.end(), 'D')) and 
(count(moves.begin(), moves.end(), 'L')==count(moves.begin(), moves.end(), 'R')))    
					return true;
       else return false;
                                                
    }
};

Python

1
2
3
4
5
6
class Solution(object):
    def judgeCircle(self, moves):
        if ((moves.count("U")==moves.count("D"))&(moves.count("L")==moves.count("R"))):
            return True
        else:
            return False

Explanation of idea

For the robot to return to the origin (0,0), every steps the robot takes need to be compensated by a step in the opposite direction. Therefore just need to check whether the steps are “balanced”.

Good solution ref.

Code

Analysis

Licensed under CC BY-NC-SA 4.0