반응형
난이도: Medium
Intuition
String에 대한 파이썬 내장함수를 알아두면 도움이 된다.
path.split("/")
# split string with "/".
# e.g.
# "/home/" -> ['', 'home', '']
# "/home//foo/" -> ['', 'home', '', 'foo', '']
# "/home/user/Documents/../Pictures" -> ['', 'home', 'user', 'Documents', '..', 'Pictures']
"/".join(stack)
# join array elements with "/"
# e.g.
# ['home', 'user', 'Pictures'] -> home/user/Pictures
# ['...', 'b', 'd'] -> .../b/d
Code
class Solution:
def simplifyPath(self, path: str) -> str:
# Initialize a stack
stack = []
# Split the input string on "/" as the delimiter
# and process each portion one by one
paths = path.split("/")
for p in paths:
# A no-op for a "." or an empty string
if p == "." or not p:
continue
# If the current component is a "..", then
# we pop an entry from the stack if it's non-empt
if p == "..":
if stack:
stack.pop()
# Finally, a legitimate directory name, so we add it
# to our stack
else:
stack.append(p)
# Stich together all the directory names together
ans = "/" + "/".join(stack)
return ans
Complexity
Time Complexity: O(N). Splitting N characters into each path -> O(N), process each path one by one -> O(N)
Space Complexity: O(N). 사실 2N인데, stack과 paths에 각각 N개가 들어있기 때문이다.
반응형
'코딩 알고리즘 문제 > Leetcode' 카테고리의 다른 글
| 162. Find Peak Element (Array, Binary Search) (0) | 2025.10.16 |
|---|---|
| 146. LRU Cache (Hash Table, Linked List, Design, Doubly-Linked List) (0) | 2025.10.16 |
| 125. Valid Palindrome (Two Pointers, String) (0) | 2025.10.16 |
| 88. Merge Sorted Array (Array, Two Pointers, Sorting) (0) | 2025.10.16 |
| 543. Diameter of Binary Tree (Tree, Depth-First Search, Binary Tree) (0) | 2025.10.16 |