[LeetCode]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

题目大意:

初始位于坐标(0, 0),UDLR分别表示向上下左右移动,求移动结束后是否位于原点。

解题思路:

模拟题

Python代码:

class Solution(object):
    def judgeCircle(self, moves):
        """
        :type moves: str
        :rtype: bool
        """
        x = y = 0
        for m in moves:
            if m == 'U': y += 1
            elif m == 'D': y -= 1
            elif m == 'R': x += 1
            elif m == 'L': x -= 1
        return x == y == 0

下面的代码也可以

Python代码:

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')

 

本文链接:http://bookshadow.com/weblog/2017/08/13/leetcode-judge-route-circle/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论