leetcode笔记--Simplify Path
来源:互联网 发布:免费图纸打印软件 编辑:程序博客网 时间:2024/05/31 06:21
题目:难度(Medium)
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".
Tags:Stack String
分析:这道题我提交了很多次才AC,主要是由于对于题目认为”pass“的输出,觉得他定义给的不够清楚,导致修改了很多次。感觉没太大意义,除了用到了栈,下面我根据他的testcase,给几组我出过错的输入输出,帮助大家理解题目的”正确目的“。
代码实现:
class Solution(object): def simplifyPath(self, path): """ :type path: str :rtype: str """ #stack列表用来维护一个栈,栈里放单独的路径名 stack = [] i = 0 #dirTmp用来存储每一个单独的路径名字 dirTmp = "" while i < len(path): if path[i] == '/': #遇到'/'则要开始考虑是否要将一个路径名入栈或出栈 if dirTmp != "": if dirTmp == "..": if len(stack) != 0: stack.pop() elif dirTmp == ".": pass else: #路径名不是'.'(跳过)或者'..'(上级),则是一个真正的路径名,入栈 stack.append(dirTmp) #处理完路径名,置空,为下一次做准备 dirTmp = "" else: #不是'/',则组成“路径名” dirTmp += path[i] i += 1 #若结尾处不是'/',则可能遗留下最后一个路径名,还需要处理 if dirTmp == "..": if len(stack) != 0: stack.pop() dirTmp = "" if dirTmp != "" and dirTmp != ".": stack.append(dirTmp) return "/" + "/".join(stack)
0 0
- leetcode笔记:Simplify Path
- leetcode笔记--Simplify Path
- LeetCode: Simplify Path
- LeetCode Simplify Path
- LeetCode : Simplify Path
- [Leetcode] Simplify Path
- [leetcode] simplify path
- [LeetCode] Simplify Path
- leetcode 100: Simplify Path
- [leetcode]Simplify Path
- [LeetCode]Simplify Path
- [leetCode] Simplify Path
- [leetcode]Simplify Path
- [leetcode] Simplify Path
- [LeetCode] Simplify Path
- leetcode simplify path
- Leetcode: Simplify Path
- LeetCode题解:Simplify Path
- Linux命令-find及xargs的使用
- IC可靠性
- xamarian studio 创建asp.net mvc razor project 报错:Could not locate Razor Host Factory type: System.We
- iphone 各种屏幕尺寸
- 粒子缩放器
- leetcode笔记--Simplify Path
- poj 1700 Crossing River
- 修改nrf52832的nfc天线引脚p09,p10为gpio
- Eclipse中的Web项目自动部署到Tomcat
- php 中isset 和 empty 的一些用法
- oracle下载
- tomcat
- 第二章:创建对话框
- 随机数和动画脚本