71. Simplify Path

Medium
要先懂几个基本的Unix-style符号的意思:
. current directory
.. parent directory

class Solution {
    public String simplifyPath(String path) {
        Stack stack = new Stack<>();
        Set set = new HashSet<>(Arrays.asList("..",".",""));
        for (String s : path.split("/")){
            if (s.equals("..") && !stack.isEmpty()){
                stack.pop();
            }
            if (!set.contains(s)){
                stack.push(s);    
            }
        }
        String res = "";
        for (String s : stack){
            res += "/" + s;
        }
        return res.length() == 0 ? "/" : res;
    }
}

你可能感兴趣的:(71. Simplify Path)