Leetcode: Simplify Path
来源:互联网 发布:alpha1机器人软件下载 编辑:程序博客网 时间:2024/06/06 13:24
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.
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"
.
不难,就是需要处理各种边界条件。
class Solution {public: string simplifyPath(string path) { string result; if (path.empty()) { return result; } stack<string> paths; string tmp; size_t cur_pos = 0; size_t prev_pos = string::npos; path.push_back('/'); for (int cur_pos = 0; cur_pos < path.size(); ++cur_pos) { if (path[cur_pos] == '/') { if (prev_pos != string::npos) { tmp = path.substr(prev_pos + 1, cur_pos - prev_pos - 1); if (!tmp.empty()) { if (tmp == "..") { if (!paths.empty()) { paths.pop(); } } else if (tmp != ".") { paths.push(tmp); } } } prev_pos = cur_pos; } } while (!paths.empty()) { result = "/" + paths.top() + result; paths.pop(); } if (result.empty()) { result = "/"; } return result; }};
class Solution {public: string simplifyPath(string path) { if (path.empty()) { return path; } stack<string> paths; int start = 0; path += "/"; for (int i = 0; i < path.size(); ++i) { if (path[i] == '/') { string tmp = path.substr(start, i - start); if (tmp == "..") { if (!paths.empty()) { paths.pop(); } } else if (!tmp.empty() && tmp != "."){ paths.push(tmp); } start = i + 1; } } string result; if (paths.empty()) { result = "/"; } else { while (!paths.empty()) { result = "/" + paths.top() + result; paths.pop(); } } return result; }};
0 0
- 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
- [LeetCode] Simplify Path
- LeetCode Simplify Path
- WM_MouseMove消息
- NEFUOJ 209 湖南修路(最小树)
- Ext3.2 布局——vbox layout
- android面试题-简答题(一)
- struts2的上传和下载
- Leetcode: Simplify Path
- 黑马程序员--java基础--io流(2)
- iOS学习笔记06—Category和Extension
- think in java interview-高级开发人员面试宝典(二)
- 二进制的世界
- 外观模式(Facade Pattern)
- Firefox支持WebGL的操作
- 漫谈 Clustering 系列 - 笔记
- 性能调优攻略