Judge Route Circle

LeetCode Judge Route Circle

先贴上题目:
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.

Example 1:

Input: "UD"
Output: true

Example 2:

Input: "LL"
Output: false

题目的意思是一个机器人初始位置在(0,0); 然后定义了上下左右四种运动,问题是经过一系列运动后该机器人能否回到初始位置;这道题比较简单,下面给出两种解法。核心思路是需要根据传入的字符串判断出R和L是否相等以及U和D是否相等。解法一先将传入的字符串转化为字符数组,然后对起进行遍历,计算出UDLR的个数,再进行判断。具体代码如下:

class Solution {
public boolean judgeCircle(String moves) {
        int u_num = 0;
        int d_num = 0;
        int l_num = 0;
        int r_num = 0; 
        char[] move = moves.toCharArray();

        for(int i = 0;i<move.length;i++){
            if(move[i] == 'U'){
                u_num = u_num + 1;
            }else if(move[i] == 'D'){
                d_num = d_num + 1;
            }else if(move[i] == 'L'){
                l_num = l_num + 1;
            }else if(move[i] == 'R'){
                r_num = r_num + 1;
            }
        }

        if(u_num==d_num && l_num==r_num){
            return true;
        }else{
            return false;
        }
}
}

第二种思路是利用string的split方法切割字符串,该方法会返回一个字符数组,通过判断切割所产生的字符数组的长度是否一致来判断机器人能否回到初始位置。要注意的是要对传入的字符串前后都拼接上” “空格字符串,以防止”UD”这中情况出错。具体代码如下:

class Solution {
public boolean judgeCircle(String moves) {
    moves = " " + moves + " ";
    return moves.split("L").length == moves.split("R").length &&      moves.split("U").length == moves.split("D").length;
}

}

第三种思路用TreeMap实现,要注意的是Integer,比较的时候应该用equals而不是==,为了防止Integer为null,在之前进行判断,若其为null,则+1;具体代码如下:

public static boolean judgeCircle(String moves) {
    char[] arr = moves.toCharArray();       
    TreeMap<Character, Integer> map = new TreeMap<>();
    for(char c : arr){
        if(map.containsKey(c)){
            int count = map.get(c);
            map.put(c, count+1);
        }else{
            map.put(c, 1);
        }
    }
        if(map.get('U') == null){
            map.put('U', 1);
        }
        if(map.get('D') == null){
            map.put('D', 1);
        }
        if(map.get('L') == null){
            map.put('L', 1);
        }
        if(map.get('R') == null){
            map.put('R', 1);
        }

        if(map.get('U').equals(map.get('D')) && map.get('L').equals(map.get('R'))){
            return true;
        }else{
            return false;
        }               
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值