Using O(1) space, and O(n) Java Solution in 9 lines


  • 0

    Just use up and left to record and go through all character to accumulate it.
    And verify the result.
    If the route is a circle, the number of up and down must be same.
    Also, the number of left and right must be same.

    public boolean judgeCircle(String moves) {
            int up = 0, left = 0;
            for(int i = 0; i < moves.length(); i++){
                char c = moves.charAt(i);
                if(c == 'U') up++;
                else if(c == 'D') up--;
                else if(c == 'L') left++;
                else left--;
            }
            return left == 0 && up == 0;
        }
    

Log in to reply
 

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