입장
- 스택 및 배열 검색을 통해 문제를 해결해야 한다는 것을 알고 있었지만 논리적으로 코드를 작성할 수 없었습니다.
- 효율적인 논리를 쓰는 훈련이 필요한 것 같습니다.
문제 링크
해결책
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