컴퓨터공학/알고리즘 문제 풀이

[LeetCode] 71. Simplify Path

TaeGyeong Lee 2023. 4. 12. 18:24

접근

  • stack과 array 탐색을 통해 문제를 해결해야 함을 알았으나 코드를 논리적으로 짜지 못하였음.
  • 효율적인 로직을 짜는 것에 대한 훈련이 필요해 보임

 

문제 링크

Simplify Path - LeetCode

 

솔루션

class Solution:
    def simplifyPath(self, path: str) -> str:
        
        stack = []
        word = ""
        
        for char in path + "/":
            if char == "/":
                # if .. -> delete lastest stack
                if word == "..":
                    if stack:
                        stack.pop()
                # if none of them and not an empty word, add stack
                elif word != "" and word != ".":
                    stack.append(word)
                word = ""
            else:
                word += char
        
        # make stack as answer format
        answer = "/" + "/".join(stack)

        return answer