美文网首页
71、Simplify Path

71、Simplify Path

作者: 小鲜贝 | 来源:发表于2018-04-19 09:33 被阅读0次

    题目:

    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.
    

    思路

    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<String> stack = new Stack<String>();
            //三种需要跳过的情况
            Set<String> skip = new HashSet<String>(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;
        }
    }
    

    相关文章

      网友评论

          本文标题:71、Simplify Path

          本文链接:https://www.haomeiwen.com/subject/hqbbkftx.html