【LeetCode】Simplify Path 解题报告
来源:互联网 发布:ubuntu mathtype 编辑:程序博客网 时间:2024/06/06 00:01
【题目】
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:
- 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"
.
【解析】
用过Linux的人都应该熟悉这个,不过其中需要注意的是 /../ 的结果是 / ,也就是说根目录的上层目录还是根目录。
【Java代码】
public class Solution { public String simplifyPath(String path) { Stack<String> stack = new Stack<String>(); int len = path.length(); int start = 0; int i = 0; while (i < len) { while (i < len && path.charAt(i) == '/') { i++; } start = i; while (i < len && path.charAt(i) != '/') { i++; } if (i > start) { String part = path.substring(start, i); if (part.equals("..")) { if (!stack.isEmpty()) stack.pop(); } else if (!part.equals(".")) { stack.push(part); } } } if (stack.isEmpty()) { return "/"; } String res = ""; while (!stack.isEmpty()) { res = "/" + stack.pop() + res; } return res; }}
0 0
- 【LeetCode】Simplify Path 解题报告
- 【LeetCode】Simplify Path 解题报告
- [LeetCode] Simplify Path 解题报告
- [leetcode] 71. Simplify Path 解题报告
- [Leetcode] 71. Simplify Path 解题报告
- Leetcode 71. Simplify Path 简化路径 解题报告
- [LeetCode]Path Sum,解题报告
- 【LeetCode】Path Sum 解题报告
- LeetCode: Simplify Path
- LeetCode Simplify Path
- LeetCode : Simplify Path
- [Leetcode] Simplify Path
- [leetcode] simplify path
- [LeetCode] Simplify Path
- leetcode 100: Simplify Path
- [leetcode]Simplify Path
- [LeetCode]Simplify Path
- [leetCode] Simplify Path
- 树状数组(一)
- C++ Primer Plus 第6版 中文版 第6章编程练习
- notification 点击响应 以及启动activity的坑
- 《剑指offer》数值的整数次方
- php中urlencode空格变成+号解决方法
- 【LeetCode】Simplify Path 解题报告
- 数据模型及类目
- HDU3068最长回文
- C++Primer第五版 1.5.1节练习
- Windows/MFC_dll生成文件___浅谈def文件(用于生成dll)
- UIlabel
- 黑马程序员——ios开发基础之C语言数据类型、运算符与输入输出
- bzoj-2151 种树
- 删除字符串中多余的空格