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

题目大概的意思是有个机器人,给定一些列动作判断它最后回到原点没。
思路很简单,回到原点换个话说就是R和L操作数量一样,U和D操作数一样即可。
public class judgeCircle {
    public static boolean judgeCircle(String moves) {
        if(moves!=null&&moves.length()>0)
        {
             int ud=0;
                int lr=0;
                for(int i=0;i<moves.length();i++)
                {
                    if(moves.charAt(i)=='U')
                    {
                        ud++;
                    }
                    if(moves.charAt(i)=='D')
                    {
                        ud--;
                    }
                    if(moves.charAt(i)=='L')
                    {
                        lr++;
                    }
                    if(moves.charAt(i)=='R')
                    {
                        lr--;
                    }
                }
                if(ud==0&&lr==0)
                {
                    return true;
                }
                else {
                    return false;
                }
        }
        else {
            return false;
        }
       
    }
    public static void main(String args[])
    {
        System.out.println(judgeCircle("UD"));
    }
}

 

posted @ 2017-12-27 17:09  icychen  阅读(166)  评论(0编辑  收藏  举报