Simplify Path

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

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

Analysis

Code

public String simplifyPath(String path){
    //keep a double ended queue to store valid file name
    Deque<String> stack = new LinkedList<String>();
    //use a hashset to store invalid name
    Set<String> skip = new HashSet<String>(Arrays.asList("..",".",""));
    for(String dir : path.split("/")){
        //meet "..", pop 
        if (dir.equals("..") && !stack.isEmpty()){stack.pop();}
        //meet valid name, push
        else if (!skip.contains(dir)) {stack.push(dir);}
    }
    String res = "";
    for (String dir:stack) res = "/" + dir +res;
    return res.isEmpty() ? "/" : res;
}

Note

  1. deque(double ended queue): use deque here since stack iterator does not behave as expected, see stackoverflow
  2. Arrays.asList(): provide a convenient way to create a fixed-size list initialized to several elements
  3. HashSet can be constructed with collection of specific elements
  4. String.split("")

Reference