Simplify Path
来源:互联网 发布:炒外汇模拟软件 编辑:程序博客网 时间:2024/06/06 01:25
1.题目
给定一个文档(Unix-style)的完全路径,请进行路径简化。
"/home/"
, => "/home"
"/a/./b/../../c/"
, => "/c"
2.算法
维护一个栈,对于每一个块(以‘/’作为分界)进行分析,如果遇到‘../’则表示要上一层,那么就是进行出栈操作,如果遇到‘./’则是停留当前,直接跳过,其他文件路径则直接进栈即可
public String simplifyPath(String path) { // Write your code here if (path == null || path.length() == 0) { return ""; } LinkedList<String> stack = new LinkedList<String>(); StringBuilder res = new StringBuilder(); int i = 0; while (i < path.length()) { int index = i; StringBuilder temp = new StringBuilder(); while (i < path.length() && path.charAt(i) != '/') { temp.append(path.charAt(i)); i++; } if (index != i) { String str = temp.toString(); if (str.equals("..")) { if (!stack.isEmpty()) { stack.pop(); } } else if (!str.equals(".")) { stack.push(str); } } i++; } if (!stack.isEmpty()) { String[] strs = stack.toArray(new String[stack.size()]); for (int j = strs.length - 1; j >= 0; j--) { res.append("/" + strs[j]); } } if (res.length() == 0) { res.append("/"); } return res.toString(); }
0 0
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- Simplify Path
- 105. Construct Binary Tree from Preorder and Inorder Traversal
- EF基础知识
- flume 的安装和入门小例子
- Java:计算器小程序
- Java内存模型——顺序一致性保证
- Simplify Path
- UNIX多线程编程(2) 线程互斥
- 判断一个字符串的所有字符是否都是唯一的(使用hash表方法)
- 1.4
- 超越影像——RSNA 2016参展随感 (一)
- Leetcode-456. 132 Pattern
- 重学JavaScript--第二章(数据类型)
- android四大组件_Activity
- 精品網站收藏