LeetCode题解(0657):判断机器人是否能回到原点(Python)

题目:原题链接(简单)

解法 时间复杂度 空间复杂度 执行用时
Ans 1 (Python) O ( N ) O(N) O(N) O ( 1 ) O(1) O(1) 56ms (66.63%)
Ans 2 (Python) O ( 1 ) O(1) O(1) 36ms (98.79%)
Ans 3 (Python)

LeetCode的Python执行用时随缘,只要时间复杂度没有明显差异,执行用时一般都在同一个量级,仅作参考意义。

解法一:

def judgeCircle(self, moves: str) -> bool:
    x = 0
    y = 0
    for move in moves:
        if move == "U":
            y += 1
        elif move == "D":
            y -= 1
        elif move == "L":
            x -= 1
        else:
            x += 1
    return x == 0 and y == 0

解法二(Pythonic):

def judgeCircle(self, moves: str) -> bool:
    return moves.count("U") == moves.count("D") and moves.count("L") == moves.count("R")

你可能感兴趣的:(LeetCode题解,Python,算法)