原题链接
https://leetcode.com/problems/simplify-path/
解题思路
这道题有两种解法,一种是用栈;另一种是用split函数
-
栈
栈的思想:
遍历path中的每一个字符,遇到’/‘不管,继续遍历,遇到不是’/‘的,开始记录字符,直到出现下一个’/’
检查这一段字符,如果是’.’,不入栈;如果是’…‘且栈不为空,pop出最后一个元素;其他情况,字符串入栈
检查完毕后,用join函数把所有字符串用’/'连接起来输出 -
split方法
用split(’/’)分割path中的元素
遍历元素:如果出现’‘和’.’,删除当前元素;如果出现’…'且不是第一个元素,删除上一个元素;否则继续往下遍历
检查完毕后依然用join函数连接
代码
# 栈
class Solution(object):
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
i = 0
cur = ''
ans_list = []
ans = '/'
while i<len(path):
start = i
while path[start]=='/':
start += 1
if start==len(path):
break
if start==len(path):
break
i = start
while path[i] != '/':
cur += path[i]
i += 1
if i==len(path):
break
if cur=='.':
cur = ''
continue
elif cur=='..':
if ans_list:
ans_list.pop()
cur = ''
continue
ans_list.append(cur)
cur = ''
ans += '/'.join(item for item in ans_list)
return ans
# split函数
class Solution(object):
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
can_path = path.split('/')
ans = '/'
i = 0
while i<len(can_path):
if not can_path[i] or can_path[i]=='.':
del can_path[i]
continue
if can_path[i]=='..':
if i==0:
can_path[i] = ''
else:
can_path.pop(i)
can_path.pop(i-1)
if i-1>=0:
i -= 1
else:
i = 0
continue
i += 1
ans += '/'.join(item for item in can_path)
return ans