Simplify Path
2016-12-17 22:03
281 查看
题目:
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
as
In this case, you should ignore redundant slashes and return
思路:
当遇到“/../"则需要返回上级目录,需检查上级目录是否为空。
当遇到"/./"则表示是本级目录,无需做任何特殊操作。
当遇到"//"则表示是本级目录,无需做任何操作。
当遇到其他字符则表示是文件夹名,无需简化。
当字符串是空或者遇到”/../”,则需要返回一个"/"。当遇见"/a//b",则需要简化为"/a/b"。
当字符串为空或者为".",不做任何操作。当字符串不为"..",则将字符串入list。当字符串为"..", 则删除最后一个(返回上级目录)。
[java] view
plain copy
public class Solution {
public static String simplifyPath(String path) {
String strs[] = path.split("/");
LinkedList<String> list = new LinkedList<>();
for (String str : strs) {
if (str.equals("..") && !list.isEmpty()) {
list.removeLast();
} else if (!str.equals(".") && !str.equals("") && !str.equals("..")) {
list.add(str);
}
}
StringBuilder result = new StringBuilder();
while (!list.isEmpty()) {
result.append("/");
result.append(list.removeFirst());
}
if (result.length() == 0) {
return "/";
}
return result.toString();
}
}
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".
思路:
当遇到“/../"则需要返回上级目录,需检查上级目录是否为空。
当遇到"/./"则表示是本级目录,无需做任何特殊操作。
当遇到"//"则表示是本级目录,无需做任何操作。
当遇到其他字符则表示是文件夹名,无需简化。
当字符串是空或者遇到”/../”,则需要返回一个"/"。当遇见"/a//b",则需要简化为"/a/b"。
当字符串为空或者为".",不做任何操作。当字符串不为"..",则将字符串入list。当字符串为"..", 则删除最后一个(返回上级目录)。
[java] view
plain copy
public class Solution {
public static String simplifyPath(String path) {
String strs[] = path.split("/");
LinkedList<String> list = new LinkedList<>();
for (String str : strs) {
if (str.equals("..") && !list.isEmpty()) {
list.removeLast();
} else if (!str.equals(".") && !str.equals("") && !str.equals("..")) {
list.add(str);
}
}
StringBuilder result = new StringBuilder();
while (!list.isEmpty()) {
result.append("/");
result.append(list.removeFirst());
}
if (result.length() == 0) {
return "/";
}
return result.toString();
}
}
相关文章推荐
- 马尔可夫平稳过程到MCMC采样
- 20155227第二次预备作业
- Bridge 模式
- 排序学习
- 【oracle】plsql连接oracle(localhost连接成功,ip连接提示无监听)问题
- SqueezeNet运用到Faster RCNN进行目标检测+OHEM
- php foreach引用赋值
- CSS3新vw, vh单位
- json-lib 与Jackson性能对比
- 4-opensatck之keystone下
- 内存的动态开辟与释放
- 绘图;PolyBezier函数和PolyBezierTo函数;PolyPolyline绘制复合线条
- 最大连续和
- bootstrap兼容问题
- 【Spring】JDBC事务管理XML配置
- 漫话中国古代史 —— 宋朝
- 位运算之十进制转二进制 十六进制转二进制
- CSS学习笔记:功能查询
- C++ primer 十二 C++中的类(一)
- Gradle编译出现OOM错误