Simple Java Solution : Time Complexity O(n) where n is the size of the given string


  • 0
    J

    Assign a cost for each of the up and down movement with same absolute value but with opposite sign. Say if up movement costs +2 then down movement would cost -2. Same for left/right movement but this time we should have cost having absolute value distinct from that assigned for up/down movement. The resultant displacement cost should be zero to form a circle.

        public boolean judgeCircle(String moves) {
            int sum = 0;
            int len = moves.length();
            while(len > 0) {
                char c = moves.charAt(len - 1);
                if (c == 'R') {
                    sum += 1;
                } 
                if (c == 'L') {
                    sum += -1;
                }
                if (c == 'U') {
                    sum += 2;
                }
                if (c == 'D') {
                    sum += -2;
                }
                len--;
            }
            return sum == 0;
        }
    }
    

  • 1
    Z

    if the input is "RRD", then this code will +1,+1, -2, end up with 0. but this is not circle.


Log in to reply
 

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