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、代码

 

 1  if(moves.size() == 0)
 2             return true;
 3 
 4         int u = 0;
 5         int d = 0;
 6         int l = 0;
 7         int r = 0;
 8 
 9         int i = 0;
10         while(i < moves.size())
11         {
12             switch (moves[i])
13             {
14                 case 'U':
15                     ++u;
16                     break;
17                 case 'D':
18                     ++d;
19                     break;
20                 case 'L':
21                     ++l;
22                     break;
23                 case 'R':
24                     ++r;
25                     break;
26                 default:
27                     break;
28             }
29             i++;
30         }
31 
32         if(u == d && l == r)
33             return true;
34 
35         return false;

 

posted @ 2018-03-26 15:30  山里的小勇子  阅读(236)  评论(0)    收藏  举报