leetcode: 71. Simplify Path
来源:互联网 发布:二手玫瑰知乎 编辑:程序博客网 时间:2024/06/04 23:36
Q
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = “/home/”, => “/home”
path = “/a/./b/../../c/”, => “/c”
Corner Cases:
Did you consider the case where path = “/../”?
In this case, you should return “/”.
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”.
AC
class Solution(object): def simplifyPath(self, path): """ :type path: str :rtype: str """ # 思路: # 1. split / 形成List # 2. 如果 .. 就 pop 前面的 # 3. 还要考虑 '///' '/...' places = [p for p in path.split("/") if p!="." and p!=""] stack = [] for p in places: if p == "..": if len(stack) > 0: stack.pop() else: stack.append(p) return "/" + "/".join(stack)# Time: O(n)# Space: O(n)class Solution2(object): def simplifyPath(self, path): stack, tokens = [], path.split("/") for token in tokens: if token == ".." and stack: stack.pop() elif token != ".." and token != "." and token: stack.append(token) return "/" + "/".join(stack)if __name__ == "__main__": assert Solution().simplifyPath("/../") == '/' assert Solution().simplifyPath("/home//foo/") == '/home/foo'
阅读全文
0 0
- LeetCode 71. Simplify Path
- LeetCode --- 71. Simplify Path
- [Leetcode] 71. Simplify Path
- [leetcode] 71.Simplify Path
- [leetcode] 71.Simplify Path
- Leetcode 71. Simplify Path
- LeetCode 71. Simplify Path
- Leetcode 71. Simplify Path
- 71. Simplify Path LeetCode
- leetcode 71. Simplify Path
- LeetCode 71. Simplify Path
- LeetCode 71. Simplify Path
- Leetcode 71. Simplify Path
- [leetcode] 71. Simplify Path
- LeetCode 71. Simplify Path
- LeetCode - 71. Simplify Path
- [LeetCode] 71. Simplify Path
- leetcode 71. Simplify Path
- spark学习-33-Spark的SerializerManager序列化管理器
- 算法—直接插入排序
- Eclipse打开报错:failed to load the jni shared library
- 关于助力砍价及微信公众号评论刷点赞及精选文章留言评论区点赞刷赞方法
- Oracle表空间管理
- leetcode: 71. Simplify Path
- python糗事百科爬虫
- EditPlus格式化XML
- 选择小程序的8大理由,让你拒绝说No
- map使用下标[]还是insert
- C/C++解析XML,pugixml库的使用
- 分布式事务-下单、支付案例
- leetcode: 72. Edit Distance
- LVM