LeetCode | 71. Simplify Path
来源:互联网 发布:java安装在d盘教程 编辑:程序博客网 时间:2024/06/03 23:43
题外话:最近每天都在反复的思考,何以解忧,唯有刷题^______________^
题目:
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"
.
输入一个字符串,表示某个文件路径,本题的目标是将该输入路径简化为形式:
simplified path = slash '/' + folder_name + ...
当出现多余的斜杠和反斜杠,需要简化为一个;当出现 '.' 为当前路径,则忽略;当出现 '..' 则返回上一级路径。
理清题意之后是思考如何解这个题目,因为需要考虑返回上一级路径,我的做法是把当前所有扫描合法的folder_name存储到一个数组里,当检测到 ''..'' 则弹出数组尾部的folder_name。
值得注意的坑是:有时候folder_name中可能会包含'.' 和 ".." ,所以每次需要判断当前扫描到点时是否符合预期约束。
代码:
string simplifyPath(string path) { int len = path.length(); if(len < 1) return path; vector<string> subpaths; string cur = "", res = ""; for(int i = 0; i<len; i++) { if(path[i] == '/' || path[i] == '\/') { if(cur != "") { subpaths.push_back(cur); cur = ""; } continue; } if(path[i] == '.') { if(cur == "") { if(i < len - 1 && path[i+1] == '.') {if(i+1 == len - 1 || (i+1 < len - 1 && path[i+2] == '/')){i++;if(subpaths.size() > 0)subpaths.pop_back();continue;} }else if(i == len - 1 || (i < len - 1 && path[i+1] == '/')){continue;} } } cur += path[i]; }if(cur != "")subpaths.push_back(cur); for(int i = 0; i<subpaths.size(); i++) { res += '/' + subpaths[i]; } if(res == "") res += '/'; return res; }
题外话:
转眼已入秋,树叶慢慢变黄,金黄色的时候一定要去拍照呀!不念过去的想法,不畏将来的困惑,就看眼前的快乐和成长。加油~
阅读全文
1 0
- 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
- Leetcode 71. Simplify Path
- [leetcode] 71. Simplify Path
- LeetCode 71. Simplify Path
- LeetCode - 71. Simplify Path
- [LeetCode] 71. Simplify Path
- leetcode 71. Simplify Path
- 程序员总结:帮助你早些明白一些道理
- Huffman文件压缩之文件夹压缩
- Judge Route Circle
- Unity笔记之-----简单的背包切换
- java实现的最小编辑距离
- LeetCode | 71. Simplify Path
- mysql添加用户
- 长安汽车悦翔V7中控台GPS导航密码
- 关于获取网络图片问题
- HDU 3790 最短路径问题
- char*str与char str[]
- Windows下好用的终端程序ConEmu
- 常用设计模式(一)Builder(构建者)模式
- 实验三 Linux文件管理