71. Simplify Path
来源:互联网 发布:stm32f103tbu6编程 编辑:程序博客网 时间:2024/06/05 17:19
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
click to show corner cases.
Corner Cases:
Solution 2 Dequeue and HashSet
- 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"
.
Solution 1 Stack
public String simplifyPath(String path) { String[] strings = path.split("/");Stack<String> stack = new Stack<String>();for (int i = 0; i < strings.length; i++) {String s = strings[i];if (s.equals("..")) {if (stack.isEmpty()) {continue;}stack.pop();} else if (s.equals(".")) {continue;} else if (s.length() == 0) {continue;} else {stack.push(s);}}StringBuilder sb = new StringBuilder();while (!stack.isEmpty()) {sb = new StringBuilder("/").append(stack.pop()).append(sb);}return sb.length() == 0 ? "/" : sb.toString(); }
Solution 2 Dequeue and HashSet
public static String simplifyPath2(String path) {Deque<String> stack = new LinkedList<>();Set<String> skip = new HashSet<>(Arrays.asList("..", ".", ""));for (String dir : path.split("/")) {if (dir.equals("..") && !stack.isEmpty()) {stack.pop();} else if (!skip.contains(dir)){stack.push(dir);}}StringBuilder sb = new StringBuilder();while(!stack.isEmpty()){sb.append("/").append(stack.pollLast());}return sb.length() == 0 ? "/" : sb.toString();}
0 0
- LeetCode 71. Simplify Path
- LeetCode --- 71. Simplify Path
- [Leetcode] 71. Simplify Path
- [leetcode] 71.Simplify Path
- 71.Simplify Path
- 71.Simplify Path
- 71. Simplify Path
- [leetcode] 71.Simplify Path
- 71. Simplify Path
- Leetcode 71. Simplify Path
- LeetCode 71. Simplify Path
- Leetcode 71. Simplify Path
- 71. Simplify Path LeetCode
- 71. Simplify Path
- 71. Simplify Path
- 71. Simplify Path
- 71. Simplify Path
- leetcode 71. Simplify Path
- 客户端到服务器端的通信过程及原理
- QT20 database values in QLineEdit or textbox if select combobox
- Thread详解12:InheritableThreadLocal的使用
- 视频播放器(四)——总结篇
- Block的深入研究之Block的内存管理
- 71. Simplify Path
- Java异常处理
- 有趣的数 算法的题解(数位DP问题)
- QT21 Display selected row from QTableView to QlineEdit
- [hdu5654 xiaoxin and his watermelon candy]区间内不同数的个数
- Client:TSocketConnection和Server:Scktsrvr关系----压缩数据传输
- 历代C++标准整理
- QT22 database values in QLineEdit or textbox if select QListView
- K-Means聚类算法实现对路透社语料reuters聚类