[LeetCode] Simplify Path
2013-11-03 14:29
274 查看
Given an absolute path for a file (Unix-style), simplify it.
For example,
path =
path =
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
such as
In this case, you should ignore redundant slashes and return
核心思想很简单,使用一个栈在内容为“..”的时候弹出前一个元素即可。这题可以偷懒,使用一个StringTokenizer类,这样的话可以很快的形成一个过滤掉所有斜杠后的内容栈。
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".
核心思想很简单,使用一个栈在内容为“..”的时候弹出前一个元素即可。这题可以偷懒,使用一个StringTokenizer类,这样的话可以很快的形成一个过滤掉所有斜杠后的内容栈。
public String simplifyPath(String path) { Stack<String> stack = new Stack<String>(); StringBuffer strBuffer = new StringBuffer(); StringTokenizer st = new StringTokenizer(path, "/"); while (st.hasMoreTokens()) { String str = st.nextToken(); // ignore "." if (".".equals(str)) { continue; } // pop out the last element else if ("..".equals(str)) { if (!stack.isEmpty()) stack.pop(); } // push the current element else { stack.push(str); } } if (stack.isEmpty()) strBuffer.append("/"); while (!stack.isEmpty()) { strBuffer.insert(0, stack.pop()); strBuffer.insert(0, "/"); } return strBuffer.toString(); }
相关文章推荐
- Leetcode: Simplify Path
- Leetcode NO.71 Simplify Path
- leetcode-Simplify Path
- [leetcode] Simplify Path
- LeetCode 071-Simplify Path
- Leetcode | Simplify Path
- leetcode面试准备:Simplify Path
- leetcode71 Simplify Path
- LeetCode 71. Simplify Path
- [LeetCode] Simplify Path 解题报告
- LeetCode | Simplify Path
- leetcode笔记:Simplify Path
- [leetcode]Simplify Path
- [leetcode] Simplify Path
- leetcode解题方案--071--Simplify Path
- Leetcode:71. Simplify Path
- leetcode Simplify Path
- leetcode || 71、Simplify Path
- leetcode笔记--Simplify Path
- [LeetCode] Simplify Path