leetcode面试准备:Simplify Path
1 题目
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".
接口:public String simplifyPath(String path)
2 思路
简化linux路径,主要对".."
进行回退操作。直观的想到用栈,在java
里,栈用Deque
的实现类LinkedList
来做。
- 对
path
进行split
- 往
stack
中添加路径,进栈,出栈 - 最后将
stack
中元素输出
3 代码
public String simplifyPath(String path) {
String[] words = path.split("/");
List<String> stack = new LinkedList<String>();
for (String s : words) {
if (s.equalsIgnoreCase("..")) {
if (!stack.isEmpty())
stack.remove(stack.size() - 1);
} else if (!(s.length() == 0 || s.equalsIgnoreCase("."))) {
stack.add(s);
}
}
String res = "";
for (String s : stack) {
res += "/" + s;
}
return res.length() == 0 ? "/" : res;
}
4 总结
栈的思想解决。