AdSense

Wednesday, January 7, 2015

Simplify Path

Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
Corner Cases:
  • Did you consider the case where path = "/../"?
    In this case, you should return "/".
  • Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
    In this case, you should ignore redundant slashes and return "/home/foo".
I was struggled to find a way to deal with "/.. /" condition since we need to remove previous added path. Using ArrayList is definitely a smart way to deal with it.

Split the path string with delimiter "/", note we need to borrow regex "+" to match one ore more "/" in  the string.
In the array of the paths, if the path is not "..", "." or ""(empty), we add it to the ArrayList, if it is "..", and if there is existing paths in the list, remove the last one.
Concatenate all the paths in the ArrayList and return the result string.


public String simplifyPath(String path) {
        if (path == null || path.length() == 0)
            return path;
        ArrayList rst = new ArrayList ();
        String[] paths = path.split("/+");//+: regex, match preceeding element one or more times
        for (String p : paths) {
            if (p.equals("..")) {
                if (rst.size() > 0) 
                    rst.remove(rst.size() - 1);
            }
            else if (!p.equals(".") && !p.equals(""))
                rst.add(p);
        }
        String simplifiedPath = "/";
        for (String p : rst) {
            simplifiedPath += p + "/";
        }
        if (simplifiedPath.length() > 1)
            simplifiedPath = simplifiedPath.substring(0, simplifiedPath.length() - 1);
        return simplifiedPath;
    }

No comments:

Post a Comment