您的位置:首页 > 其它

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

"/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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: