Leetcode 71. Simplify Path

来源:互联网 发布:最为突出的大数据环境 编辑:程序博客网 时间:2024/06/05 16:01

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();}


0 0