题目描述

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

解决方案 - C++

class Solution {
public:
    bool judgeCircle(string moves) {
        int x = 0, y = 0;
        for(int i = 0; i < moves.length(); i++){
            if(moves.substr(i, 1) == "R"){
                x--;
            }
            if(moves.substr(i, 1) == "L"){
                x++;
            }
            if(moves.substr(i, 1) == "U"){
                y++;
            }
            if(moves.substr(i, 1) == "D"){
                y--;
            }
        }
        if(x == 0 && y == 0){
            return true;
        }else{
            return false;
        }
    } 
};

解题思路
设置初始坐标为(0,0),根据上UDLR指示调整坐标,判断最后坐标的位置是否为起始位置。

Submission Details

62 / 62 test cases passed.
Status: Accepted
Runtime: 39 ms

[C++] [Java] Clean Code

Tips:

1.加强版for循环
2.使用switchif判断快
3.Java toCharArray()方法

C++

class Solution {
public:
    bool judgeCircle(string moves) {
        int v = 0;
        int h = 0;
        for (char ch : moves) {
            switch (ch) {
                case 'U' : v++; break;
                case 'D' : v--; break;
                case 'R' : h++; break;
                case 'L' : h--; break;
            }
        }
        return v == 0 && h == 0;
    }
};

Submission Details

62 / 62 test cases passed.
Status: Accepted
Runtime: 19 ms

Java

class Solution{
    public boolean judgeCircle(String moves) {
        int v = 0, h = 0;
        for (char move : moves.toCharArray()) {
            switch (move) {
                case 'U': v++; break;
                case 'D': v--; break;
                case 'R': h++; break;
                case 'L': h--; break;
            }
        }
        return v == 0 && h == 0;
    } 
}

Submission Details

62 / 62 test cases passed.
Status: Accepted
Runtime: 11 ms 

Python one liner

class Solution(object):
    def judgeCircle(self, moves):
        """
        :type moves: str
        :rtype: bool
        """ 
        return moves.count('L') == moves.count('R') and moves.count('U') == moves.count('D')

Submission Details

62 / 62 test cases passed.
Status: Accepted
Runtime: 42 ms 

计算向左和向右的次数是否相同,计算向上和向下的次数相同。若都相同,则回到原地。


afra
225 声望23 粉丝

你的努力程度之低 远还没有到比拼天赋的需要。