Java Easy to Understand Solution O(n)


  • 0
    B

    Explanation
    For this problem, we can think of a 'L' move cancelling out a 'R' move, and vice-versa. The same logic applies to 'U' and 'D' moves.

    So, we are really just checking if all the moves cancel each other out at the end.

    Time Complexity
    The time complexity is O(n) where n is the number of characters in input moves.

    class Solution {
        public boolean judgeCircle(String moves) {
            int up = 0;
            int down = 0;
            int left = 0;
            int right = 0;
            
            for (int i = 0; i < moves.length(); i++) {
                if (moves.charAt(i) == 'U') {
                    up++;
                } else if (moves.charAt(i) == 'D') {
                    down++;
                } else if (moves.charAt(i) == 'L') {
                    left++;
                } else {
                    right++;
                }
            }
            return (up == down && left == right);
        }
    }
    

Log in to reply
 

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