当前位置 : 首页 » 文章分类 :  算法  »  LeetCode.657.Judge Route Circle

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

解题过程

这个题也很简单,只要R和L、U和D能成对的消掉就是能回到起始点,所以思路是一次遍历统计字符串中RLUD的个数,RL个数相等且UD个数相等就是能回到起点。

代码如下,一次AC:

package _657_JudgeRouteCircle;

class Solution {
    public boolean judgeCircle(String moves) {
        int Lnum=0, Rnum=0, Unum=0, Dnum=0;
        for(int i=0; i<moves.length(); i++) {
            switch (moves.charAt(i)) {
            case 'L':
                Lnum++;
                break;
            case 'R':
                Rnum++;
                break;
            case 'U':
                Unum++;
                break;
            case 'D':
                Dnum++;
                break;                
            default:
                break;
            }
        }
        if (Lnum==Rnum && Unum==Dnum) {
            return true;
        }else {
            return false;
        }
    }
}

public class JudgeRouteCircle{
    public static void main(String[] args){
        Solution solution = new Solution();
        System.out.println(solution.judgeCircle("UD"));
    }
}

AC后看了几个别人的代码,思路完全一样,都是统计LRUD个数然后判断相等,只不过转为char数组操作就快,直接操作java String类就慢。


GitHub代码


上一篇 LeetCode.557.Reverse Words in a String III

下一篇 java.util.Collections

阅读
322
阅读预计2分钟
创建日期 2018-01-04
修改日期 2018-01-11
类别
百度推荐