

https://leetcode.com/problems/simplify-path/
1.입력 경로를 데크(queue)로 변환하여 문자열을 하나씩 처리한다.(파이선 Split 함수를 사용했으면 이렇게 할 필요가 없이 효율적으로 처리했을 듯하다)
2.searchFile 함수를 사용하여 경로에서 다음 파일 이름을 추출하고 처리되지 않은 경로(queue)를 반환한다.
3.파일 이름이 "/.."인 경우 상위 디렉토리로 이동하고, 상위 디렉토리로 이동한 만큼 경로에서 이전 파일을 제거한다.
4.파일 이름이 "/." 또는 "/"인 경우 아무 작업도 수행하지 않고 무시한다.
5.그 외의 경우 파일 이름을 경로에 추가하고 FileMemory에 저장한다.
모든 파일을 처리한 후, 최종 결과 문자열을 반환합니다. 만약 경로가 비어있다면 루트 디렉토리인 "/"를 반환ㅎ한다.
class Solution:
def simplifyPath(self, path: str) -> str:
def searchFile(queuepath):
queue = queuepath
File = ""
File+=(queue.popleft())
while queue:
if queue[0]=="/":
break
File+=(queue.popleft())
return (queue),(File)
queue=deque(path)
ans=""
FileMemory = deque()
while queue:
queue,nextFile = searchFile(queue)
if nextFile =="/..":
currFile=FileMemory.pop() if FileMemory else ""
ans=ans[:-len(currFile)]
elif nextFile == "/." or nextFile == "/" :
continue
else:
ans+=nextFile
FileMemory.append(nextFile)
return ans if len(ans)>0 else "/"
솔루션 코드
from collections import deque
class Solution:
def simplifyPath(self, path: str) -> str:
stack = deque()
parts = path.split('/') # 경로를 슬래시로 분할
for part in parts:
if part == '..':
if stack:
stack.pop() # 상위 디렉토리로 이동
elif part and part != '.':
stack.append(part) # 현재 디렉토리 추가
simplified_path = '/' + '/'.join(stack)
return simplified_path if simplified_path else '/'

python.split
path가 "/a/./b/../../c/"인 경우, path.split('/')를 사용하면 다음과 같이 분할되게 됨
["","a",".","b","..","..","c".""]
'/'.join(stack): 스택(stack)에 있는 모든 문자열 요소를 슬래시(/)로 연결함. 예를 들어, 스택에 ['a', 'b', 'c']가 있다면 이를 'a/b/c'를 반환