[LC]657. Judge Route Circle

来源:互联网 发布:宽带多重网络怎么回事 编辑:程序博客网 时间:2024/06/10 16:10

一、问题描述

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即可。

class Solution {    public boolean judgeCircle(String moves) {        if(moves.length() == 0){            return true;        }                int horizon = 0;        int vertical = 0;        char[] c = moves.toCharArray();                for(int i = 0; i < c.length; i ++){            switch(c[i]){                case 'U':                    vertical ++;                    break;                case 'D':                     vertical --;                    break;                case 'L':                    horizon --;                    break;                case 'R':                    horizon ++;                    break;                default:                    break;            }        }        if(horizon == 0 && vertical == 0){            return true;        }        else{            return false;        }            }}

三、淫奇技巧

思路都差不多,就是有人的代码写的好漂亮~计数用的是split后数组长度。炫技时记得在原字符串首位加字符……

 public boolean judgeCircle(String moves) {        moves=" " + moves + " ";        return moves.split("L").length==moves.split("R").length && moves.split("U").length == moves.split("D").length;    }

四、追加问题

暂时没想到