资讯专栏INFORMATION COLUMN

[LeetCode] 71. Simplify Path

superw / 2768人阅读

Problem

Given an absolute path for a file (Unix-style), simplify it.

For example,

path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
path = "/a/../../b/../c//.//", => "/c"        //here: b is cancelled out, a is cancelled out
path = "/a//b////c/d//././/..", => "/a/b/c"   //here d is cancelled out

In a UNIX-style file system, a period (".") refers to the current directory, so it can be ignored in a simplified path. Additionally, a double period ("..") moves up a directory, so it cancels out whatever the last directory was. For more information, look here: https://en.wikipedia.org/wiki...

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".

Solution
class Solution {
    public String simplifyPath(String path) {
        Deque stack = new ArrayDeque<>();
        Set ignore = new HashSet<>(Arrays.asList("", ".", ".."));
        for (String dir: path.split("/")) {
            if (!stack.isEmpty() && dir.equals("..")) stack.pop();
            if (!ignore.contains(dir)) stack.push(dir);
        }
        String res = "";
        while (!stack.isEmpty()) {
            res = "/"+stack.pop()+res;
        }
        if (res.equals("")) return "/";
        return res;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/72713.html

相关文章

  • leetcode71. Simplify Path

    摘要:标题文字简化风格的绝对路径。我们可以首先将所有的内容从中分离出来,然后分别处理。这里我们需要用到堆栈的数据结构。堆栈有很多种实现方式,中的类类都可以实现其功能。我们将读到的路径入栈,根据操作符出栈,最后将栈中剩余的元素组织成路径返回即可。 标题文字 Given an absolute path for a file (Unix-style), simplify it. For exa...

    darkerXi 评论0 收藏0
  • 71. Simplify Path

    摘要:题目解答的规则如下三种需要跳过的情况当遇到时,需要向前进出来的顺序是反的,所以加的时候,把最新出来的路径加在前面 题目:Given an absolute path for a file (Unix-style), simplify it. For example,path = /home/, => /homepath = /a/./b/../../c/, => /cclick to ...

    EdwardUp 评论0 收藏0
  • [Leetcode] Simplify Path 化简路径

    摘要:栈法复杂度时间空间思路思路很简单,先将整个路径按照分开来,然后用一个栈,遇到时弹出一个,遇到和空字符串则不变,遇到正常路径则压入栈中。注意如果结果为空,要返回一个弹出栈时要先检查栈是否为空代码 Simplify Path Given an absolute path for a file (Unix-style), simplify it. For example, path = /...

    liangzai_cool 评论0 收藏0
  • Leetcode71. 简化路径

    摘要:题目给定一个文档的完全路径,请进行路径简化。例如,边界情况你是否考虑了路径的情况在这种情况下,你需返回。此外,路径中也可能包含多个斜杠,如。文化和社会被恐惧所塑造,在将来这无疑也不会消失。 题目 给定一个文档 (Unix-style) 的完全路径,请进行路径简化。 例如,path = /home/, => /homepath = /a/./b/../../c/, => /c 边界情况:...

    liuchengxu 评论0 收藏0
  • Leetcode71. 简化路径

    摘要:题目给定一个文档的完全路径,请进行路径简化。例如,边界情况你是否考虑了路径的情况在这种情况下,你需返回。此外,路径中也可能包含多个斜杠,如。文化和社会被恐惧所塑造,在将来这无疑也不会消失。 题目 给定一个文档 (Unix-style) 的完全路径,请进行路径简化。 例如,path = /home/, => /homepath = /a/./b/../../c/, => /c 边界情况:...

    afishhhhh 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<