71、Simplify Path

题目:

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;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容