Python solution with detailed explanation


  • 2
    G

    Judge Route Circle https://leetcode.com/problems/judge-route-circle/description/

    Balance U with D and R with L

    class Solution(object):
        def judgeCircle(self, moves):
            """
            :type moves: str
            :rtype: bool
            """
            return (moves.count("U") == moves.count("D")) and (moves.count("R") == moves.count("L"))
    

    Simulate movements

    • Imagine we start with origin. After all movements, we must be back at origin.
    class Solution(object):
        def judgeCircle(self, moves):
            """
            :type moves: str
            :rtype: bool
            """
            x,y = 0,0
            offsets = {"U":[0,1], "D":[0,-1], "R":[1,0], "L":[-1,0]}
            for move in moves:
                x,y = x+offsets[move][0], y+offsets[move][1]
            return (x == 0) and (y == 0)
    

    User a counter and balance U/D and R/L

    from collections import Counter    
    class Solution(object):
        def judgeCircle(self, moves):
            """
            :type moves: str
            :rtype: bool
            """
            ctr = Counter(moves)
            ctr += Counter("UDRL")
            return (ctr["U"] == ctr["D"]) and (ctr["R"] == ctr["L"])
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.