zoukankan      html  css  js  c++  java
  • 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

    题意:在(0,0)处有一个机器人,给它一系列动作,判断机器人完成这一系列动作后能否返回原位置。
    动作为:R右;L左;U上;D下。移动顺序是由这四个方向字符组成的字符串,输出true或false,表示机器人是否回到原位置。

    思路:假定:向右走加1, 向左走减1;向上走加2,向下走减2。
    将字符串转成字符数组,定义一个求和变量sum,逐个遍历每个字符,对每个字符根据其对应的数字进行加减,如果遍历完成后,sum为0,说明机器人回到了原位置;否则就没有回到原位置。代码如下:

    public boolean judgeCircle(String moves) {
            char[] chars = moves.toCharArray();
            int sum = 0;
            for (int i = 0; i < chars.length; i++) {
                if (chars[i] == 'R')
                    sum += 1;
                else if (chars[i] == 'L')
                    sum -= 1;
                else if (chars[i] == 'U')
                    sum += 2;
                else if (chars[i] == 'D')
                    sum -= 2;
            }
            return sum == 0 ? true : false;
        }
     
  • 相关阅读:
    k-means聚类JAVA实例
    钓鱼站点以世界杯足球赛为饵,收集个人资料
    南桥--特殊回文数
    Oracle 数据文件管理
    hihoCoder #1142 : 三分求极值
    时间复杂度和空间复杂度[数据结构]
    poj 3635 Full Tank? ( 图上dp )
    FastQC结果详解
    毕业设计常见问题
    centos 查看USB接口的版本
  • 原文地址:https://www.cnblogs.com/zeroingToOne/p/7843253.html
Copyright © 2011-2022 走看看