Leetcode 071 简化路径 Python C++
2018-08-08 09:31
429 查看
题目:
给定一个文档 (Unix-style) 的完全路径,请进行路径简化。
例如,
path =
"/home/", =>
"/home"
path =
"/a/./b/../../c/", =>
"/c"
边界情况:
- 你是否考虑了 路径 =
"/../"
的情况?
在这种情况下,你需返回"/"
。 - 此外,路径中也可能包含多个斜杠
'/'
,如"/home//foo/"
。
在这种情况下,你可忽略多余的斜杠,返回"/home/foo"
。
每天更新一道python or C++ leetcode题,力求讲解清晰准确,客官们可以点赞或者关注。
算法过程:
遍历原路径,找到/之间的内容,根据当前内容判断是把v中的最后路径弹出还是加入当前内容。(v用来储存之前的路径名)
然后根据最终得到的v组合我们的字符串答案。
Python:
[code]class Solution(object): def simplifyPath(self, path): """ :type path: str :rtype: str """ stack,i,ans = [],0,'' while i < len(path): j = i + 1 while j < len(path) and path[j] != '/': j += 1 #tmp即路径名 tmp = path[i + 1:j] if tmp != '': if tmp == '..': if stack !=[]: stack.pop() elif tmp != '.': stack.append(tmp) i = j if stack == []: return '/' for k in stack: ans += '/' + k return ans
C++:
[code]class Solution { public: string simplifyPath(string path) { vector<string> v;//用来储存斜杠里的内容 int i = 0;//遍历指针 while (i < path.size()) {//开始遍历 while (path[i] == '/' && i < path.size()) ++i;//找到第一个非'/'的内容 if (i == path.size()) break; int start = i;//开始起点 while (path[i] != '/' && i < path.size()) ++i;//找到第一个结束的'/' int end = i - 1; string s = path.substr(start, end - start + 1);//截取那一段路径内容 if (s == "..") {//如果是双点,则说明跳回上一层,所以上一个路径在简化后的版本里失效 if (!v.empty()) v.pop_back(); } else if (s != ".") {//如果不是.,证明是有效内容,于是我们加入v中 v.push_back(s); } } if (v.empty()) return "/";//根据边界给出的提示完成 string res; for (int i = 0; i < v.size(); ++i) { res += '/' + v[i];//把v中的每一项再重新组成字符串 } return res; } };
总结:C++中切割字符串的方法是需要指名开始位置与长度
相关文章推荐
- [C++]LeetCode: 117 Simplify Path (简化Unix路径 list双向链表)
- LeetCode 26 — Remove Duplicates from Sorted Array(C++ Java Python)
- LeetCode 62 — Unique Paths(C++ Java Python)
- 【LeetCode】【Python】【C++】2. Add Two Numbers代码实现
- Leetcode_sort-colors(c++ and python updated)
- [LeetCode]题解(python):071-Simplify Path
- LeetCode 70 — Climbing Stairs(C++ Java Python)
- [LeetCode] 71. Simplify Path 简化路径
- Leetcode 83 删除排序链表中的重复元素 Python C++ 史上最详细题解系列
- [LeetCode] 012. Integer to Roman (Medium) (C++/Java/Python)
- [LeetCode] 022. Generate Parentheses (Medium) (C++/Java/Python)
- c++导入python模块,如果python脚本与exe不在同一目录,需要增加搜索路径
- LeetCode 112 — Path Sum(C++ Java Python)
- LeetCode 34 — Search for a Range(C++ Java Python)
- leetcode_[python/C++] 179. Largest Number(数字组合成最大数)
- Leetcode 80 删除排序数组中的重复项 II Python C++ 史上最详细题解系列
- Leetcode_wildcard-matching(c++ and python version)
- Leetcode 81 搜索旋转排序数组 II Python C++ 史上最详细题解系列
- Simplify Path 简化文件路径@LeetCode
- [LeetCode] 016. 3Sum Closest (Medium) (C++/Java/Python)