Post

문제풀이 - 657. Robot Return to Origin




문제

image alt 문제

https://leetcode.com/problems/robot-return-to-origin/

1. 접근

RLUD 수를 세고, RL 상쇄시키고, UD를 상쇄.

문자열의 길이가 홀수면 모두 상쇄될 수가 없음 -> False

2. 제출한 답

1
2
3
4
5
6
7
8
from collections import Counter

class Solution:
    def judgeCircle(self, moves: str) -> bool:
        if len(moves) % 2 == 0:
            result: Counter = Counter(moves)
            return result['R'] == result['L'] and result['U'] == result['D']
        return False

시간 복잡도

Counter 객체를 만들 때의 O(n)이다.

3. 로직이 좀 더 눈에 보이게

1
2
3
4
5
6
7
8
9
from collections import Counter

class Solution:
    def judgeCircle(self, moves: str) -> bool:
        if len(moves) % 2 == 0:
            result: Counter = Counter(moves)
            return result['R'] - result['L'] == 0 and result['U'] - result['D'] == 0
        return False

This post is licensed under CC BY 4.0 by the author.