[Leetcode] 71. Simplify Path 解题报告
来源:互联网 发布:阿里云服务器个人备案 编辑:程序博客网 时间:2024/06/06 18:10
题目:
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"
.
思路:
首先熟悉一下Unix-style的路径构成规则:
字符 含义(英文) 含义(中文)
实现技巧:1)可以在path的最后加入一个"/",这样可以统一提取两个“/”之间的字符串,简化程序逻辑;2)采用vector来模拟stack,因为vector除了具备stack的所有功能之外,还有从前到后顺序访问元素的优势,这样可以避免最后对stack中的元素进行反转的额外时间复杂度开销。
代码:
class Solution {public: string simplifyPath(string path) { vector<string> st; // we use vecctor to simulate stack path += '/'; // for easier programming for (int i = 1; i < path.size(); i++) { int pos = path.find('/', i); string tem = path.substr(i, pos - i); if (tem == "..") { if(st.size() > 0) { st.pop_back(); } } else if (tem.size() > 0 && tem != ".") { st.push_back("/" + tem); } i = pos; } string ans; for (auto val: st) { ans += val; } return ans.size() == 0? "/" : ans; }};
0 0
- [leetcode] 71. Simplify Path 解题报告
- [Leetcode] 71. Simplify Path 解题报告
- 【LeetCode】Simplify Path 解题报告
- 【LeetCode】Simplify Path 解题报告
- [LeetCode] Simplify Path 解题报告
- Leetcode 71. Simplify Path 简化路径 解题报告
- LeetCode 71. Simplify Path
- LeetCode --- 71. Simplify Path
- [Leetcode] 71. Simplify Path
- [leetcode] 71.Simplify Path
- [leetcode] 71.Simplify Path
- Leetcode 71. Simplify Path
- LeetCode 71. Simplify Path
- Leetcode 71. Simplify Path
- 71. Simplify Path LeetCode
- leetcode 71. Simplify Path
- LeetCode 71. Simplify Path
- LeetCode 71. Simplify Path
- gitlab服务器搭建教程
- 【算法】滑动窗方法问题总结
- [Leetcode] 70. Climbing Stairs 解题报告
- PHP弱类型导致的安全问题--md5
- Android studio jni 生成 头文件
- [Leetcode] 71. Simplify Path 解题报告
- PHP弱类型--strcmp()
- 九度OJ-1172-哈夫曼树
- 748UVa迷宫探索
- UVa 1589 象棋 xiangqi 问题。 判断是否将军致死。
- [Leetcode] 72. Edit Distance 解题报告
- 构建本地vim编程环境
- iOS 沙盒文件路径获取
- Effective Java 读书笔记——39:必要时进行保护性拷贝