leetCode题解 寻找运动环

时间:2023-03-09 21:32:11
leetCode题解 寻找运动环

1、题目描述

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.

题目的意思是,如果一个可以上下左右运动,分别记做 ‘U’ ,'D',‘L’,‘R’。将一个机器人的运动序列记做一个string ,根据这个string 判断机器人是否回到了原点。

2、问题分析

特例是机器人没有动,即string的长度是0,那么机器人就在原位。

机器人回到原位的条件是,上下运动的步数相等 并且 左右运动的步数相等。遍历一次string ,分别记录上下左右运动的次数,然后比较每个方向上运动的次数。如果  R == L  &&  U  == D  ,那么机器人回到了原点。

3、代码

  if(moves.size() == )
return true; int u = ;
int d = ;
int l = ;
int r = ; int i = ;
while(i < moves.size())
{
switch (moves[i])
{
case 'U':
++u;
break;
case 'D':
++d;
break;
case 'L':
++l;
break;
case 'R':
++r;
break;
default:
break;
}
i++;
} if(u == d && l == r)
return true; return false;