[LC]657. Judge Route Circle

本文介绍了一种通过分析机器人移动指令来判断其是否能回到原始位置的方法。利用向量加法原理,通过统计水平和垂直方向上的位移,最终确定机器人是否完成闭环运动。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、问题描述

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即可。

class Solution {
    public boolean judgeCircle(String moves) {
        if(moves.length() == 0){
            return true;
        }
        
        int horizon = 0;
        int vertical = 0;
        char[] c = moves.toCharArray();
        
        for(int i = 0; i < c.length; i ++){
            switch(c[i]){
                case 'U':
                    vertical ++;
                    break;
                case 'D':
                     vertical --;
                    break;
                case 'L':
                    horizon --;
                    break;
                case 'R':
                    horizon ++;
                    break;
                default:
                    break;
            }
        }
        if(horizon == 0 && vertical == 0){
            return true;
        }
        else{
            return false;
        }
        
    }
}

三、淫奇技巧

思路都差不多,就是有人的代码写的好漂亮~计数用的是split后数组长度。炫技时记得在原字符串首位加字符……

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

四、追加问题

暂时没想到


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值