Monday, May 8, 2017

71. 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".



Solution:

We split the string with "/".

Therefore, the entry could be "..", "", ".", and valid directory.

If we find a "..", and the paths is not empty, we can remove the last element.

Else if we find a string is not "" or ".", we know it is a valid directory. Hence we add it to the paths.

Finally, we build up the paths string with "/" as splitter, and remove the last "/" if necessary.



Code:


public class Solution {
    public String simplifyPath(String path) {
        String result = "/";
        ArrayList<String> paths = new ArrayList<>();
        for (String s : path.split("/")) {
            if (s.equals("..")) {
                if (paths.size() > 0) {
                    paths.remove(paths.size() - 1);
                }
            }
            else if (!s.equals("") && !s.equals(".")) {
                paths.add(s);
            }
        }
        for (String dir : paths) {
            result = result + dir + "/";
        }
        if (result.length() > 1) {
            result = result.substring(0, result.length() - 1);
        }
        return result;
    }
}