题解 | #简化目录路径#
简化目录路径
https://www.nowcoder.com/practice/3177bcbfd947409ba833efb5a5b4a24c
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param path string字符串
# @return string字符串
#
class Solution:
def simplifyPath(self , path: str) -> str:
# write code here
s = [] #栈
p = path.split("/") #用“/”分割;如/home//为["","home","",""], 这一步同时处理“///”
for item in p:
if item == "..": #当为..退到上一级
if s:
s.pop()
elif item and item !=".": #当不为.,入栈
s.append(item)
return "/"+"/".join(s) #组合返回
查看11道真题和解析