Lucid solution -Java 22 ms (using x,y Co-Ordinates and If-else ladder.)


  • 0
    R
    class Solution {
        public boolean judgeCircle(String moves) {
                int x=0,y=0;
                char[] c=moves.toCharArray();
                for(char i: c)
                {
                    if(i=='U')
                        y+=1;
                    else if(i=='D')
                        y-=1;
                    else if(i=='L')
                        x-=1;
                    else if(i=='R')
                        x+=1;
                    else
                        return false;
                }
            if(x==0 && y==0)
                return true;
            else 
                return false;
        }
    }
    

    First we convert the string to a character array, then we use an enhanced for-loop to go through all the characters of the array, we initialize the X and Y co-ordinates to be zero, and then if we encounter special characters then we increment or decrement by 1. In the end, if both the X and Y co-ordinates are the same as we initialized we can return true. Also we return false if the string contains any character other then "U", "D", "L" or "R".


Log in to reply
 

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