Leetcode71: Simplify Path
来源:互联网 发布:怎么看淘宝店铺的销量 编辑:程序博客网 时间:2024/06/11 19:48
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
给出一个unix的完全路径,然后简化这个路径。主要的就是 /.. 表示返回上级目录, /. 表示在当前目录。
思路:
因为要是返回上级目录,就是退出当前目录,很容易联想到栈的性质。所以用栈存储访问的目录的顺序。在扫描给的路径的过程中,注意一下 /.. 和 /. 两种情况即可。还有最后一位不一定是'/',所以也要判断一下。提示里面有要求注意 /../ 的这种情况,需要在pop前判断一个栈是否为空即可。
代码:
class Solution {public: string simplifyPath(string path){ stack<string> res;int len=path.size();string s="";bool canAdd=true;for(int i=0; i<len; i++){if(path[i]=='.'){if(i+1<len && path[i+1]=='/' && i>=1 && path[i-1]=='/'){}else if(i+2<len && path[i+2]=='/' && i>=1 && path[i-1]=='/'){if(!res.empty()) res.pop();i++;}else s+=path[i];}else if(path[i]!='/') s+=path[i];else{if(s!="") res.push(s);s="";}}if(path[len-1]!='/'){if(len-2>=0 && path[len-1]=='.' && path[len-2]=='/'){}else if(len-3>=0 && path[len-1]=='.' && path[len-2]=='.' && path[len-3]=='/'){if(!res.empty()) res.pop();}else res.push(s);}string ans;string str;if(res.empty()) return "/";while(!res.empty()){str=res.top();res.pop();reverse(str.begin(), str.end());str+='/';ans+=str;}reverse(ans.begin(), ans.end());return ans;}};
0 0
- Simplify Path Leetcode71
- LeetCode71. Simplify Path
- Leetcode71: Simplify Path
- leetcode71. Simplify Path
- LeetCode71 Simplify Path
- LeetCode71 Simplify Path java题解
- LeetCode71——Simplify Path
- 算法设计与分析HW8:LeetCode71.Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- C# 第11章
- ubuntu开启mysql远程端口 3306
- WebRTC VideoEngine综合应用示例(三)——集成X264编码和ffmpeg解码
- 十一章 上机5
- gitlab下对php代码进行检测
- Leetcode71: Simplify Path
- 浅谈Java内存及GC
- UNP环境
- Android ORMLite 框架的入门用法
- 考虑下面的程序的执行
- 虚拟机中的集中网络链接方式
- 今天开始写写博客,记录一下学习的感悟
- UTILS
- 提高系统开发效率的“银弹”——X-series可视化大规模应用开发工具集