leetcode题解-71. Simplify Path

题意:对于给定的类Unix系统的文件路径,对其进行简化。

分析:在Unix系统中”.”表示当前路径,”..”表示上一级路径。

这道题要使用一个栈,来保存当前的路径状况。我们首先需要按照“/”将地址进行分割,分割出不同的操作:
1、如果是空或者“.”,那么当前没有什么地址变动,地址栈不需要变动 。
2、如果是“..” 则需要出栈(如果栈为空则不操作)因为这是返回上级目录的符号 。
3、其他情况压栈。

class Solution {
    public static String simplifyPath(String path) {
        Deque<String> stack = new LinkedList<>();
        Set<String> 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 res = "";
        for (String dir : stack) res = "/" + dir + res;
        return res.isEmpty() ? "/" : res;
    }
}

你可能感兴趣的:(Leetcode题解,leetcode)