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;
        }
     
  • 相关阅读:
    第十天python3 函数的销毁
    第九天python3 闭包
    第八天pyhton3 函数的返回值、作用域
    第七天python3 函数、参数及参数解构(二)
    音视频不同步排查方法
    第六天python3 函数、参数及参数解构(一)
    第五天python3 内建函数总结
    第四天python3 python解析式-生成器-迭代器

    [转载]基于Java反序列化
  • 原文地址:https://www.cnblogs.com/zeroingToOne/p/7843253.html
Copyright © 2011-2022 走看看