Leetcode 657 判断路线成圈


初始位置 (0, 0) 处有一个机器人。给出它的一系列动作,判断这个机器人的移动路线是否形成一个圆圈,换言之就是判断它是否会移回到原来的位置

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

示例 1:

输入: "UD"
输出: true

示例 2:

输入: "LL"
输出: false
C语言
#include<stdio.h>
int judgeCircle(char *moves,int size){
        int x = 0,y = 0,i = 0;
        for(i=0;i<size;i++){
                if(*(moves+i) == 'U') y--;
                else if(*(moves+i) == 'D') y++;
                else if(*(moves+i) == 'L') x--;
                else if(*(moves+i) == 'R') x++;
        }
        return x==0 && y==0;
}
int main(){
        char ch[] = "UD";
        printf("%d\n",judgeCircle(ch,2));
        return 0;
}
Java语言
public class JudegeCircle {
    public static void main(String[] args) {
        JudegeCircle judegeCircle = new JudegeCircle();
        System.out.println(judegeCircle.judgeCircle("UD"));
    }
    public boolean judgeCircle(String moves) {
        int x = 0, y = 0;
        for (char move: moves.toCharArray()) {
            if (move == 'U') y--;
            else if (move == 'D') y++;
            else if (move == 'L') x--;
            else if (move == 'R') x++;
        }
        return x == 0 && y == 0;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值