简化路径思路:
根据给定的字符串利用“/”分割字符串,分割得到的列表会有以下几种情况:
- ”//“ 会分割出空字符串
- 一个点'.'
- 两个点'..'
- 只包含英文字母、数字或 _ 的目录名
对于1和2无需处理,对于3,需要弹出栈顶元素,对于4需要入栈
class Solution:
def simplifyPath(self, path: str) -> str:
stack=[]
for ch in path:
stack.append(ch)
if len(stack)>2 and stack[-1]=='.' and stack[-2]='/':
stack.pop(),stack.pop()
elif len(stack)>3 and stack[-1]==stack[-2]=='.' and stack[-3]='/':
stack.pop(),stack.pop(),stack.pop(),stack.pop(),stack.pop()
return ''.join(stack)