[LeetCode]657.Judge Route Circle

题目描述:

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

思路:

给定一个字符串代表机器人移动的方向,U表示上,D表示下,L表示左,R表示右,判断最后是否回到原点
*设置原点为(0,0),x表示横坐标,y表示纵坐标

 1 public class Solution657 {
 2      public boolean judgeCircle(String moves) {
 3             int x = 0,y = 0;
 4             for(int i = 0; i < moves.length();i++){
 5                 if(moves.charAt(i)=='U') y++;
 6                 if(moves.charAt(i)=='D') y--;
 7                 if(moves.charAt(i)=='L') x--;
 8                 if(moves.charAt(i)=='R') x++;
 9             }
10             if(x==0&&y==0) return true;
11             else return false;
12         }
13     public static void main(String[] args) {
14         // TODO Auto-generated method stub
15         Solution657 solution657 = new Solution657();
16         String moves = "UDUDLRL";
17         if(solution657.judgeCircle(moves)==true){
18             System.out.println(1);
19         }else {
20             System.out.println(0);
21         }
22     }
23 
24 }

 

posted @ 2018-03-05 10:24  zlz099  阅读(144)  评论(0编辑  收藏  举报