标签(空格分隔): LeetCodepython
做者: 负雪明烛
id: fuxuemingzhu
我的博客: http://fuxuemingzhu.me/linux
题目地址:https://leetcode.com/problems/simplify-path/description/app
Given an absolute path for a file (Unix-style), simplify it.ide
For example,this
path = "/home/", => "/home" path = "/a/./b/../../c/", => "/c"
Corner Cases:spa
Did you consider the case where path = “/../”?
In this case, you should return “/”.code
Another corner case is the path might contain multiple slashes ‘/’ together, such as “/home//foo/”.
In this case, you should ignore redundant slashes and return “/home/foo”.ip
简化linux路径。leetcode
看到这种来来回回,增增删删的题,通常都想到用栈。字符串
咱们把字符串按照/分割以后就获得了每一个文件的目录,而后判断路径是添加仍是向上层进行返回。这个题很简单了。
有一个地方犯了小错误,不能写成if dir == ‘..’ and stack: stack.pop()。这样的话若是栈是空的,就把..进栈了。
class Solution(object): def simplifyPath(self, path): """ :type path: str :rtype: str """ stack = list() dirs = path.split('/') for dir in dirs: if not dir or dir == '.': continue if dir == '..': if stack: stack.pop() else: stack.append(dir) return '/' + '/'.join(stack)
2018 年 6 月 26 日 ———— 早睡早起