Leetcode 71. Simplify Path
2017-02-27 05:24
253 查看
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
注意: 两点(..)是返回上级,一点是不动。
题目很简单,简化路径。
1、一看到题目,首先反应是采用stack
2、用deque的话方便之后用stringbuilder
3、拿到string后用trim
4、之后就是看到字母就offer,看到.. 就poll。
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
注意: 两点(..)是返回上级,一点是不动。
题目很简单,简化路径。
1、一看到题目,首先反应是采用stack
2、用deque的话方便之后用stringbuilder
3、拿到string后用trim
4、之后就是看到字母就offer,看到.. 就poll。
public String simplifyPath(String path) { if (path == null || path.length() == 0) {return new String();} path = path.trim(); Deque<String> q = new LinkedList<>(); for (String s : path.split("/")) { if (s.equals("..")) { if (!q.isEmpty()) { q.pollLast(); } } else if (!s.equals(".") && !s.equals("")) { q.offerLast(s); } } StringBuilder sb = new StringBuilder(); while (!q.isEmpty()) { sb.append("/").append(q.pollFirst()); } return sb.length() == 0 ? new String("/") : sb.toString(); }
相关文章推荐
- leetcode 71. Simplify Path
- Leetcode 71. Simplify Path
- Leetcode:71. Simplify Path
- Leetcode 71. Simplify Path
- Leetcode-71. Simplify Path
- Leetcode 71. Simplify Path
- LeetCode 71. Simplify Path
- leetcode: 71. Simplify Path
- leetcode-71. Simplify Path
- leetcode 71. Simplify Path
- Leetcode 71. Simplify Path
- LeetCode 71. Simplify Path
- LeetCode 71. Simplify Path
- LeetCode 71. Simplify Path
- [Leetcode] Simplify Path
- LeetCode - Refresh - Simplify Path
- 【leetcode】Simplify Path
- Simplify Path [LeetCode]
- LeetCode(71) Simplify Path
- LeetCode刷题(38)--Simplify Path