leetCode 71.Simplify Path(化简路径) 解题思路和方法
2015-07-17 16:45
381 查看
Simplify Path
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".
思路:此题是有些坑爹的,原因就是...的类型也算合法,其路径格式不是windows,是Linux的,对于Linux小白来说,路径还是不好考虑的。
在解的过程中,如果是对字符遍历将会有些麻烦,最简单的办法就是对字符串按“/”分割数组,然后按情况操作。具体代码如下:
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".
思路:此题是有些坑爹的,原因就是...的类型也算合法,其路径格式不是windows,是Linux的,对于Linux小白来说,路径还是不好考虑的。
在解的过程中,如果是对字符遍历将会有些麻烦,最简单的办法就是对字符串按“/”分割数组,然后按情况操作。具体代码如下:
public class Solution { public String simplifyPath(String path) { //将//都简化成/ path = path.replaceAll("/{2,}","/"); System.out.println(path); Stack<String> st = new Stack<String>(); //按/分割数组 String[] p = path.split("/"); for(int i = 0; i < p.length; i++){ //..表示后退一个路径 if(p[i].equals("..")){ if(!st.isEmpty())//不为空才后退 st.pop(); } //.忽视,表示当前路径 else if(!p[i].equals(".") ){ st.push(p[i]); } } //现在栈里的就是简化的路径 String s = ""; while(!st.isEmpty()){ s = "/" + st.pop() + s;//先进后出 } s = "/" + s;//补上开头的/ if(s.length() > 1) s = s.replaceAll("/$","").replaceAll("/{1,}", "/");//去除结尾的/ return s; } }
相关文章推荐
- Fastjson序列化map时,保留map的进出栈顺序的方法
- 《Effective C++》——条款20:宁以pass-by-reference-to-const替换pass-by-value
- bash数组
- zabbix监控之redis自动发现并监控
- spurious wakeup虚假唤醒(待总结)
- fiddler进行弱网测试
- https://github.com/Bilibili/ijkplayer
- IOS中的深拷贝与浅拷贝
- 算法的封装与切换——策略模式(Stragety Pattern)
- 单例设计模式及内存划分
- 运维资料汇总
- Java client 访问 memcached
- 状态机思路在程序设计中的应用
- leetCode 70.Climbing Stairs (爬楼梯) 解题思路和方法
- 新开了微博,小伙伴们可以关注下哦
- java 并发多线程异步
- Java client 访问 memcached
- Xmpp integration with Asterisk
- (转) Android平台上关于IM的实践总结
- 4、iOS传值的方法-Notifaction反向传值