[LeetCode]Simplify Path
2016-11-27 23:30
232 查看
https://leetcode.com/problems/simplify-path/
string.split的时候如果两个标志之间没有值也会返回一个空字符串,stack用ArrayDeque,“/..”和“/home//test”都是合法输入
public class Solution {
public String simplifyPath(String path) {
if (path == null) return path;
String[] arr = path.split("/");
Deque<String> stack = new ArrayDeque<>();
for (int i = 0; i < arr.length; i++) {
if (arr[i].equals(".") || arr[i].length() == 0) continue;
else if (arr[i].equals("..")) {
if (!stack.isEmpty()) stack.pop();
}
else stack.push(arr[i]);
}
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()) {
sb.insert(0, "/" + stack.pop());
}
return sb.length() == 0 ? "/" : sb.toString();
}
}
string.split的时候如果两个标志之间没有值也会返回一个空字符串,stack用ArrayDeque,“/..”和“/home//test”都是合法输入
public class Solution {
public String simplifyPath(String path) {
if (path == null) return path;
String[] arr = path.split("/");
Deque<String> stack = new ArrayDeque<>();
for (int i = 0; i < arr.length; i++) {
if (arr[i].equals(".") || arr[i].length() == 0) continue;
else if (arr[i].equals("..")) {
if (!stack.isEmpty()) stack.pop();
}
else stack.push(arr[i]);
}
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()) {
sb.insert(0, "/" + stack.pop());
}
return sb.length() == 0 ? "/" : sb.toString();
}
}
相关文章推荐
- 【leetcode】【71】Simplify Path
- [LeetCode] Simplify Path
- LeetCode 71 Simplify Path(Python详解及实现)
- leetcode 71. Simplify Path
- [Leetcode]Simplify Path
- [LeetCode] Simplify Path 简化路径
- LeetCode-Simplify Path
- 【LeetCode】71. Simplify Path
- leetcode 71 Simplify Path
- [LeetCode]Simplify Path
- Java for LeetCode 071 Simplify Path
- [leetcode] Simplify Path
- [leetcode]Simplify Path
- [leetcode刷题系列]Simplify Path
- leetcode 71. Simplify Path
- Leetcode: Simplify Path
- [Leetcode] Simplify path 简化路径
- LeetCode: Simplify Path
- Leetcode 71. Simplify Path
- [leetcode] Simplify Path