[Leetcode 60] 71 Simplify Path
2013-05-26 12:33
501 查看
Problem:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path =
path =
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
In this case, you should ignore redundant slashes and return
Analysis:
Simulation problem, with the help of a vector keeping record of the current path and either push a new path node or pop the older path node or do nothing to maintain the final path.
Need to pay special attention to those corner cases.
Code:
View Code
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".
Analysis:
Simulation problem, with the help of a vector keeping record of the current path and either push a new path node or pop the older path node or do nothing to maintain the final path.
Need to pay special attention to those corner cases.
Code:
class Solution { public: string simplifyPath(string path) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<string> stack; stack.push_back("/"); int p1 = 0, p2 = 0; while (true) { while (path[p1] == '/' && p1<path.size()) p1++; p2 = p1+1; while (path[p2] != '/' && p2<path.size()) p2++; if (p2 > path.size()) break; string tmp = path.substr(p1, p2-p1); if (tmp == "..") { if (stack.size() != 1) stack.pop_back(); } else if (tmp == ".") ;//do nothing else stack.push_back(tmp); p1 = p2; } if (stack.size() == 1) return "/"; else { string tmp; for (int i=1; i<stack.size(); i++) tmp += "/" + stack[i]; return tmp; } } };
View Code
相关文章推荐
- LeetCode 71 Simplify Path(Python详解及实现)
- LeetCode_OJ【71】Simplify Path
- leetcode 71 Simplify Path
- LeetCode(71) Simplify Path
- 【leetcode】【71】Simplify Path
- leetcode-71 simplify path
- [leetcode 71] Simplify Path
- leetcode71 Simplify Path
- [LeetCode]71 Simplify Path(模拟)
- LeetCode_71---Simplify Path
- LeetCode71——Simplify Path
- LeetCode71 Simplify Path 解题报告
- LeetCode 71 Simplify Path
- 【LeetCode】C# 71、Simplify Path
- [leetcode-71]Simplify Path(C)
- LeetCode71 Simplify Path
- LeetCode 71 Simplify Path (栈)
- LeetCode 71 Simplify Path
- LeetCode(71) Simplify Path
- LeetCode(71) Simplify Path