Simplify Path
2015-12-11 20:02
435 查看
Given an absolute path for a file (Unix-style), simplify it.
For example,
path =
path =
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
In this case, you should ignore redundant slashes and return
模拟栈
Next challenges: (H) Largest Rectangle in Histogram (E) Min Stack (M) Reverse Words in a String II
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".
模拟栈
/* 1.遇到./,当前位置-2, 2.遇到../,当前位置-3,然后回退到上一个斜杠处 测试用例: . .. /. /.. /... /./ /../ /// /./ /../ /.../ /..../../../../../../ /a../././../ /a.../././.. */ class Solution { public: string simplifyPath(string path) { int i=0,j=0; if(path.size()>0){ path.push_back('/'); } string res(path.size(),' '); while(i<path.size()){ if(i>0 && path[i]==res[j-1] && path[i]=='/') { i++; continue; } res[j++] = path[i]; if(path[i]=='/'){ int pre_level_start = i-3>=0? i-3:0; if(path.substr(pre_level_start,i-pre_level_start+1)=="/../"){ j-=4; while(j-1>=0 && res[j-1]!='/') --j; if(j==0){ j=1; } }else{ pre_level_start = i-2>=0? i-2:0; if(path.substr(pre_level_start,i-pre_level_start+1)=="/./"){ j-=2; } } } i++; } if(j>1 && res[j-1]=='/') --j; res.erase(res.begin()+j,res.end()); return res; } };
Next challenges: (H) Largest Rectangle in Histogram (E) Min Stack (M) Reverse Words in a String II
相关文章推荐
- ZZULIOJ 1812: sort (字符串乱搞)
- Android开机启动Activity或者Service方法
- 【LEETCODE】312-Burst Balloons
- Mac系统的隐藏文件查看与隐藏
- scanf格式控制符
- Struts2学习——(十)Struts2标签IV
- 3:输入一个整数,求这个数的阶乘
- C#中两个static函数互相递归调用时,递归结果不正确的问题
- linux那些命令
- JAVA性能优化之设计模式
- datagrid动态生成列并动态赋值
- 20151211小问题
- JavaScript全讲-它能做什么
- 关于commons-configuration的 PropertiesConfiguration读配置文件时的默认分隔符
- 对象序列化成XML存储,XML反序列换成对象
- iOS开发53-Github和Source Tree的使用
- 《软件分析和系统设计》读书笔记之一
- 复制文件
- C# 多个Main()方法
- Audio相关Log