题目原址
https://leetcode.com/problems/simplify-path/description/
题目描述
Given 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 "/".
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".
解题思路
给定一个绝对路径,将其化为最简的形式返回来。使用栈来完成这道题,这里有几个特殊的情况:
- 如果是“.”或者空,则保持不动,因为表示的是当前的路径
- 如果是“..”,则说明要返回上级菜单,因此需要从栈中弹出元素
- 除了上述两种情况,其他的情况就直接压栈就可以了
AC代码
class Solution {
public String simplifyPath(String path) {
Stack<String> stack = new Stack<>();
while(path.length() > 0) {
int start = path.indexOf("/"); //当前字符串的第一个/位置
path = path.substring(start + 1); //将当前字符串的第一个/去掉
int end = path.indexOf("/"); //当前字符串的第二个/位置
if(end == -1) { //如果字符串已经没有/了,则将字符串末尾位置置于字符串尾
end = path.length();
}
String part = path.substring(0, end); //取得两个//中间的字符串
path = path.substring(end); //更新path的值,其值等于第二个/后面的元素的值
if(part.equals("") || part.equals(".")) // 如果中间的字符串为空或者为.则什么都不做
continue;
if(part.equals("..")){ //如果中间的字符串为..,则表示返回上级菜单,所以要从栈中弹出栈顶元素
if(!stack.isEmpty())
stack.pop();
}else {
stack.push("/" + part); //否则,将中间的字符串压入栈中
}
}
String ret = "";
while(!stack.isEmpty()) {
ret = stack.pop() + ret;
}
if(ret.length() == 0)
ret = "/";
return ret;
}
}