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 ( N ) O(N) O(N) 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")
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页