Skip to main content

71. Simplify Path

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

Python

  • 乍看有點複雜,但其實沒什麼難度直直寫過去...
class Solution:
def simplifyPath(self, path: str) -> str:
stack = []

cur = ''
for letter in path:
if letter == '/':
if cur == '..':
if stack:
stack.pop()
cur = ''
elif cur == '.':
cur = ''
elif cur:
stack.append(cur)
cur = ''
else:
cur += letter

if cur == '..':
if stack:
stack.pop()
elif cur != '.':
stack.append(cur)