1104. 机器人能否返回原点

描述

最初,机器人位于(0, 0)处。 给定一系列动作,判断该机器人的移动轨迹是否是一个环,这意味着它最终会回到原来的位置。

移动的顺序由字符串表示。 每个动作都由一个字符表示。 有效的机器人移动是R(右),L(左),U(上)和D(下)。 输出应该为true或false,表示机器人是否回到原点。

您在真实的面试中是否遇到过这个题?

样例

样例1:

输入: "UD"
输出: true

样例2:

输入: "LL"
输出: false
1104. Judge Route Circle

Description
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 finally.

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.

public class Solution {
    /**
     * @param moves: a sequence of its moves
     * @return: if this robot makes a circle
     */
    public boolean judgeCircle(String moves) {
        // Write your code here
       int horizon = 0;
       int height  = 0;
       for(char c: moves.toCharArray()){
           switch(c){
                case 'L':{ --horizon; break;}
                case 'R':{ ++horizon; break;}
                case 'U':{ --height;  break;}
                default: { ++height;}
           }
       }
       return horizon==0&&height==0? true:false;
    }
}
public class Solution {
    /**
     * @param moves: a sequence of its moves
     * @return: if this robot makes a circle
     */
	 public static boolean judgeCircle(String moves) {
	        // Write your code here
	        char[] move = moves.toCharArray();
	        
	        int up = 0;
	        int down = 0;
	        int left = 0;
	        int right = 0;
	        for (char c : move) {
				if(c == 'U') {
					up++;
				}else if(c == 'D') {
					down++;
				}else if(c == 'L') {
					left++;
				}else {
					right++;
				}
	        
	        }
	        
	        if(up == down && left == right) {
	        	return true;
	        }else {
	        	return false;
	        }
	        
	}
}
posted @ 2019-04-02 21:47  故人叹  阅读(219)  评论(0编辑  收藏  举报