Simplify Path
2016-07-17 01:02
309 查看
Given an absolute path for a file (Unix-style), simplify it.
Have you met this question in a real interview?
Yes
Example
Challenge
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
Use StringBuilder
Have you met this question in a real interview?
Yes
Example
"/home/", =>
"/home"
"/a/./b/../../c/", =>
"/c"
Challenge
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".
public class Solution { /** * @param path the original path * @return the simplified path * 归下类的话,有四种字符串: 1. "/":为目录分隔符,用来分隔两个目录。 2. ".":当前目录 3. "..":上层目录 4. 其他字符串:目录名 简化的核心是要找出所有的目录,并且如果遇到"..",需要删除上一个目录。 */ public static String simplifyPath(String path) { if (path == null || path.length() == 0) return path; String[] subPath = path.split("/"); Stack<String> stack = new Stack<String>(); for (int i = 0; i < subPath.length; i++) { String str = subPath[i]; if (!(str.equals(".") || str.isEmpty())) { // for . and empty string, we do nothing. if (str.equals("..")) { // we need to remove one upper directory if (stack.size() >= 1) { stack.pop(); } } else { stack.push("/" + str); } } } StringBuilder sb = new StringBuilder(); while (!stack.isEmpty()) { sb.insert(0, stack.pop()); } return sb.length() == 0 ? "/" : sb.toString(); } }
Use StringBuilder
public class Solution { public static String simplifyPath(String path) { if (path == null || path.length() == 0) return path; String[] subPath = path.split("/"); StringBuilder sb = new StringBuilder(""); for (int i = 0; i < subPath.length; i++) { String str = subPath[i]; if (!(str.equals(".") || str.isEmpty())) { // for . and empty string, we do nothing. if (str.equals("..")) { // we need to remove one upper directory if (sb.length() > 1) { int k = sb.length() - 1; while (sb.length() >= 1 && sb.charAt(k) != '/') { sb.deleteCharAt(k); k--; } sb.deleteCharAt(k); // "delete the last /" } } else { sb.append("/"); sb.append(str); } } } if (sb.length() == 0) { return "/"; } return sb.toString(); } }
相关文章推荐
- Hibernate注解
- 数学百家
- IntelliJ IDEA 14.x 快捷键/个性化设置
- 数学百家
- HTML5画布属性
- win主机用web.config和httpd.ini实现301重定向
- Oracle函数及操作符
- Memcache的mutex设计模式 -- 高并发解决方案
- java与xml之JDOM生成和解析XML文档
- hdu 1069 Monkey and Banana DP
- TableLayout 的collapseColumns、shrinkColumns、stretchColumns
- 单例模式
- 安卓实战开发之JNI入门及高效的配置(android studio一键生成.h,so及方法签名)
- 如何使用iTunes与iTools导出微信聊天记录
- 导出/导入Eclipse的workspace配置(备份Eclipse配置)
- [LeetCode] 16. 3Sum Closest
- python 实现 knn分类算法 (Iris 数据集)
- URL、URN、URI的区别?
- 部署exchange2010三合一:之四:安装exchange
- HTML5和CSS3实例教程[总结一]