657. 机器人能否返回原点『简单』

题目来源于力扣(LeetCode

一、题目

657. 机器人能否返回原点

题目相关标签:字符串

二、解题思路

3.1 数学计算方式

  1. 遍历 moves 数组,出现 L 字符时加 1,出现 R 字符时减 1

  2. 出现 U 字符时加 2,出现 D 字符时减 2

  3. 最后**结果仍然为 0 **时,说明可以返回原点

  4. 思路:L 字符与 R 字符的个数相同并且 U 字符与 D 字符的个数相同时,机器人才能返回原点

3.2 哈希表方式

  1. 通过哈希数组来记录 moves 数组中元素 “L”, “R”, “U”, “D” 出现的次数

  2. 当哈希数组中元素 “L” 与 “R” 出现的次数相同,并且元素 “U” 与 “D” 出现的次数相同时,返回 true

  3. 否则返回 false

三、代码实现

3.1 数学计算方式

public static boolean judgeCircle(String moves) {
    int num = 0;
    char[] arr = moves.toCharArray();
    for (char j : arr) {
        // L 与 R,U 与 D 都会相互抵消
        if (j == 'L') {
            num += 1;
        } else if (j == 'R') {
            num -= 1;
        } else if (j == 'U') {
            num += 2;
        } else {
            num -= 2;
        }
    }
    // 结果仍然为 0 时,说明能够回到原点
    return num == 0;
}

3.2 哈希表方式

public static boolean judgeCircle(String moves) {
    // 哈希映射数组,索引为键,索引上的元素为 moves 数组中字符元素出现的次数
    int[] bucket = new int[26];
    for (char i : moves.toCharArray()) {
        bucket[i - 'A'] += 1;
    }
    // L 与 R 且 U 与 D 的个数相同时,说明能够返回原点
    return bucket['R' - 'A'] == bucket['L' - 'A']
        && bucket['U' - 'A'] == bucket['D' - 'A'];
}

四、执行用时

4.1 数学计算方式

4.2 哈希表方式

五、部分测试用例

public static void main(String[] args) {
    String moves = "UD";  // output:true
//    String moves = "LL";  // output:false
    boolean result = judgeCircle(moves);
    System.out.println(result);
}
posted @ 2020-05-24 20:57  知音12138  阅读(180)  评论(0编辑  收藏  举报