소프트웨어에 대한 모든 것

LeetCode 풀기 - 71. Simplify Path 본문

알고리즘/LeetCode

LeetCode 풀기 - 71. Simplify Path

앤테바 2022. 3. 15. 04:14
반응형

71. Simplify Path

https://leetcode.com/problems/simplify-path/

 

Simplify Path - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제)

솔루션1)

class Solution:
    def simplifyPath(self, path: str) -> str:
        # any multiple consecutive slashes (i.e. '//') are treated as a single slash '/'
        path = path.replace('//', '/')

        # The path starts with a single slash '/'
        canonical_path = ['/']

        for dir_name in path.split('/')[1:]:
            if not dir_name:
                continue

            if dir_name == '..':
                if len(canonical_path) > 1:
                    # 마지막의 디렉토리 이름과 '/'를 제거
                    canonical_path = canonical_path[:-2]
            elif dir_name == '.':
                # do nothing
                pass
            else:
                canonical_path.append(dir_name)
                canonical_path.append('/')

        # the path does not end with a trailing '/
        while len(canonical_path) > 1 and canonical_path[-1] == '/':
            canonical_path = canonical_path[:-1]

        return ''.join(canonical_path)

솔루션2)

discuss를 보니 정말 간결하게 풀었네요.

class Solution:    
    def simplifyPath(self, path: str) -> str:
        stack = []
        for dir_name in path.split('/'):
            if dir_name == '..':
                if stack:
                    stack.pop()
            elif dir_name and dir_name != '.':
                stack.append(dir_name)
        return '/' + '/'.join(stack)

함께 보면 좋은 글:

https://leetcode.com/problems/simplify-path/discuss/25691/9-lines-of-Python-code

 

반응형
Comments