Judge Route Circle

来源:互联网 发布:笔记本网卡mac地址修改 编辑:程序博客网 时间:2024/06/08 13:40

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;        }               }