算法分析与设计课程(10):【leetcode】Simplify Path
2017-04-30 16:23
615 查看
Description:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path =
path =
click to show corner cases.
算法分析:
题目的要求是输出Unix下的最简路径,Unix文件的根目录为"/","."表示当前目录,".."表示上级目录。
例如:
输入1:
/../a/b/c/./..
输出1:
/a/b
模拟整个过程:
1. "/" 根目录
2. ".." 跳转上级目录,上级目录为空,所以依旧处于 "/"
3. "a" 进入子目录a,目前处于 "/a"
4. "b" 进入子目录b,目前处于 "/a/b"
5. "c" 进入子目录c,目前处于 "/a/b/c"
6. "." 当前目录,不操作,仍处于 "/a/b/c"
7. ".." 返回上级目录,最终为 "/a/b"
使用一个栈来解决问题。遇到'..'弹栈,遇到'.'不操作,其他情况下压栈。
代码如下:
class Solution:
# @param path, a string
# @return a string
def simplifyPath(self, path):
stack = []
i = 0
res = ''
while i < len(path):
end = i+1
while end < len(path) and path[end] != "/":
end += 1
sub=path[i+1:end]
if len(sub) > 0:
if sub == "..":
if stack != []: stack.pop()
elif sub != ".":
stack.append(sub)
i = end
if stack == []: return "/"
for i in stack:
res += "/"+i
return res
Given an absolute path for a file (Unix-style), simplify it.
For example,
path =
"/home/", =>
"/home"
path =
"/a/./b/../../c/", =>
"/c"
click to show corner cases.
算法分析:
题目的要求是输出Unix下的最简路径,Unix文件的根目录为"/","."表示当前目录,".."表示上级目录。
例如:
输入1:
/../a/b/c/./..
输出1:
/a/b
模拟整个过程:
1. "/" 根目录
2. ".." 跳转上级目录,上级目录为空,所以依旧处于 "/"
3. "a" 进入子目录a,目前处于 "/a"
4. "b" 进入子目录b,目前处于 "/a/b"
5. "c" 进入子目录c,目前处于 "/a/b/c"
6. "." 当前目录,不操作,仍处于 "/a/b/c"
7. ".." 返回上级目录,最终为 "/a/b"
使用一个栈来解决问题。遇到'..'弹栈,遇到'.'不操作,其他情况下压栈。
代码如下:
class Solution:
# @param path, a string
# @return a string
def simplifyPath(self, path):
stack = []
i = 0
res = ''
while i < len(path):
end = i+1
while end < len(path) and path[end] != "/":
end += 1
sub=path[i+1:end]
if len(sub) > 0:
if sub == "..":
if stack != []: stack.pop()
elif sub != ".":
stack.append(sub)
i = end
if stack == []: return "/"
for i in stack:
res += "/"+i
return res
相关文章推荐
- 算法分析与设计课程——LeetCode刷题之3Sum
- 算法分析与设计课程(19):【leetcode】Ugly Number II
- 算法分析与设计课程——LeetCode刷题之Valid Parentheses
- 算法分析与设计课程(11):【leetcode】Gray Code
- 算法分析与设计课程——LeetCode刷题之 Spiral Matrix
- 算法分析与设计课程(8):【leetcode】Sudoku Solver
- 算法分析与设计课程——LeetCode刷题之 Rotate Image
- 算法分析与设计课程10——523. Continuous Subarray Sum
- 算法分析与设计课程——LeetCode刷题之Search for a Range
- 算法分析与设计课程——LeetCode刷题之Remove Duplicates from Sorted Array
- 算法分析与设计课程(16):【leetcode】 Integer to Roman
- 算法分析与设计课程(3):【leetcode】Permutations
- 算法分析与设计课程——LeetCode刷题之 Pow(x, n)
- 算法分析与设计课程——LeetCode刷题之Reverse Integer
- 算法分析与设计课程——LeetCode刷题之 Merge k Sorted Lists
- 算法分析与设计课程——LeetCode刷题之4Sum
- 算法分析与设计课程(5):【leetcode】Search for a Range
- 算法分析与设计课程(14):【leetcode】 Maximal Square
- 算法分析与设计丨第六周丨LeetCode(10)——Best Time to Buy and Sell Stock(Easy)
- 算法分析与设计课程(7):【leetcode】Reverse Nodes in k-Group