Java solution


  • 0
    B
    /*
     * Initially, there is a Robot at position (0, 0). 
     * Given a sequence of its moves, judge if this robot makes a circle, 
     * which means it moves back to the original place.
    
    The move sequence is represented by a string. 
    And each move is represent by a character. 
    The valid robot moves are R (Right), L (Left), U (Up) and D (down). 
    The output should be true or false representing whether the robot makes a circle.
    Input: "UD"
    Output: true
    Input: "LL"
    Output: false
    
     */
    public class RobotProblem {
    	public boolean judgeCircle(String moves) {
            int up=0,down=0,left=0,right=0;      
            char[] ch=moves.toCharArray();
            for(int i=0;i<ch.length;i++){
                switch(ch[i]) {
                    case 'U':
                    up++;
                break;
                    case 'D':
                    down++;
                break;
                case 'L':
                left++;
                break;
                case 'R':
                right++;
                break;
                default:
                	System.out.println(ch[i]+" is an invalid move");
                break;
              //invalid move
                }
                    
            }
            if((up-down==0)&(right-left==0))
                return true;
            else
                return false;
            
        }
    
    }
    
    

Log in to reply
 

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