您的位置:首页 > 其它

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。

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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: