资讯专栏INFORMATION COLUMN

71. Simplify Path

EdwardUp / 1661人阅读

摘要:题目解答的规则如下三种需要跳过的情况当遇到时,需要向前进出来的顺序是反的,所以加的时候,把最新出来的路径加在前面

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

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

解答:
unix style path的规则如下:
/ -> root
/a -> in (a)
. -> THIS dir path
/a/./ -> still in /a
/a/./b -> in /a/b
.. -> go "up" one level
/a/./b/.. -> /a/b/.. -> /a
/a/./b/../.. -> /a/.. -> /
/a/./b/../../c -> /c

public class Solution {
    public String simplifyPath(String path) {
        Stack stack = new Stack();
        //三种需要跳过的情况
        Set skip = new HashSet(Arrays.asList("..", ".", ""));
        
        for (String dir : path.split("/")) {
            //当遇到..时,需要向前进
            if (dir.equals("..") && !stack.isEmpty()) {
                stack.pop();
            } else if (!skip.contains(dir)) {
                stack.push(dir);
            }
        }
        String result = "";
        if (stack.isEmpty()) result += "/";
        while (!stack.isEmpty()) {
            //pop出来的顺序是反的,所以加的时候,把最新pop出来的路径加在前面
            result = "/" + stack.pop() + result;
        }
        return result;
    }
}

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

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

相关文章

  • [LeetCode] 71. Simplify Path

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

    superw 评论0 收藏0
  • leetcode71. Simplify Path

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

    darkerXi 评论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
  • [LintCode] Simplify Path [字符串操作]

    摘要:,可以用函数去掉所有,然后多考虑一个中间为空的。关于语句的一个特点我们对和其实都是不做操作,然而,两个可以都,但是不能都不做操作。像这样这样这两个就都会等价于下一个就会出错。 Problem Given an absolute path for a file (Unix-style), simplify it. Example /home/, => /home //去掉末尾的slash...

    leanxi 评论0 收藏0
  • 基于CentOS 7.2 的Laravel 生成环境部署

    摘要:一前期准备最新版本的安装镜像我所使用的是一个可以运行的主机或虚拟机远程登录客户端我用的是二开始部署现在安装基本都是图形界面,这里我就不一一截图了,我们直接进入部署环节。 一、前期准备: 最新版本的CentOS7.2 安装镜像(我所使用的是minimal) 一个可以运行CentOS的主机或虚拟机 SSH远程登录客户端(我用的是SecureCRT) 二、开始部署 现在Linux安装基本...

    junfeng777 评论0 收藏0

发表评论

0条评论

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