Total Accepted: 74685
Total Submissions: 309287
Difficulty: Medium
Contributors: Admin
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"
.
解法1: Stack
比较清楚的思路是, 用一个stack来存储每一级的path, 如果遇到”.”则跳过,如果遇到”..”表明要前进一级, 那就把当前的栈顶的path弹出
最后栈就是存放的reverse过的path,一个个把他们串起来就可以了.
C++
也可以用一个deque来解决,这样在结束了之后不需要reverse stack里的结果。