Simplify Path
来源:互联网 发布:通用电气知乎 编辑:程序博客网 时间:2024/06/03 06:00
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:
一道考察细节的题目,但是这个的test case不全,没有考虑../../的情况。- 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"
.
分析:
1. path的分界符为 “/", 所以可以以slash为区分。
2. 当两个/中间为空或者为.的时候,则可忽略
3. 当两个中间为..的时候,则抹掉上一次层
4. 其他为合法, push back
左后返回结果的时候要注意如果为空的话需要返回一个'/'。
所以整个就是维护一个stack,然后考虑三种情况,最后返回一个以'/'为头的string. 比较tricky的是getline(stringstream(path), tmp, '/'). 这个是基本功,但是没想到。学习了
class Solution {public: string simplifyPath(string path) { string res,tmp; stringstream ss(path); vector<string> stk; while(getline(ss,tmp,'/')){ if (tmp=="." || tmp=="") continue; if (tmp==".." && !stk.empty()){ stk.pop_back(); } if (tmp!="..") stk.push_back(tmp); } for (int i=0; i<stk.size(); i++){ res+="/"+stk[i]; } return res.empty()? "/":res; }};
0 0
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Microsoft Techdays 2015 - Etat de lieux JavaScript
- 【Unity】常用脚本类的继承关系(入门篇)
- proteus C51源代码调试不能显示源代码的问题
- svnserve配置文件详析
- keil与proteus联调方法
- Simplify Path
- 109.Convert Sorted List to Binary Search Tree Leetcode Python
- 11.2.0.4.0 PatchSet 补丁号 13390677
- Oracle11g各版本下载地址
- 【C#】结构体与类的比较
- PHP网站使用JavaScript和Iframe简单实现部分刷新效果
- Oracle安装介质及补丁集下载地址
- cocos2d-x 文本框
- HashMap vs. TreeMap vs. Hashtable vs. LinkedHashMap