Simplify Path

来源:互联网 发布:淘宝店铺添加收藏 编辑:程序博客网 时间:2024/06/14 19:13

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

For example,
path = “/home/”, => “/home”
path = “/a/./b/../../c/”, => “/c”

思路:将路径根据“/”进行分割,得到去掉“/”的数组,然后将数组的内容放入栈中,当遇到“..”时,就把栈中的一个元素pop出来,当遇到“.”或者“”时,过滤到不添加到栈中。
最后遍历栈中元素便可得到简化后的路径了。
代码如下:

public String simplifyPath(String path) {        Deque<String> stack = new LinkedList<>();        Set set = new HashSet<String>();        set.add("");        set.add(".");        set.add("..");        for (String dir : path.split("/")) {            if ("..".equals(dir) && !stack.isEmpty()) {                stack.pop();            }            if (!set.contains(dir)) {                stack.push(dir);            }        }        String result = "";        for (String dir : stack) {            result = "/" + dir + result;        }        return result.isEmpty() ? "/" : result;    }