71. Simplify Path
Leetcode String StackGiven an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
Corner Cases:
- Did you consider the case where path =
"/../"
?- In this case, you should return
"/"
.
- 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"
.
- In this case, you should ignore redundant slashes and return
/**
* Given an absolute path for a file (Unix-style), simplify it.
*
* https://leetcode.com/problems/simplify-path/description/
*
* 使用stack处理,需要注意得是可能会出现"/.."的情况,
* 所以要判断stack.isEmpty();
* 也需要注意空的情况,需要判断stack.size()==0。
*
*
*
*/
public class Q71SimplifyPath {
public static String simplifyPath(String path) {
Stack<String> stack = new Stack<>();
for (String s: path.split("/")) {
switch (s) {
case "":
break;
case ".":
break;
case "..":
if (!stack.isEmpty())
stack.pop();
break;
default:
stack.push(s);
break;
}
}
if (stack.size()==0) {
return "/";
}
StringBuilder newPath = new StringBuilder();
for (String s: stack) {
newPath.append("/");
newPath.append(s);
}
return newPath.toString();
}
}