leetcode

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

public String simplifyPath(String path) {
        if (path==null||path.isEmpty()) {
            return "";
        }

        if (path.length()==1) {
            return "/";
        }

        List<String> paths = new ArrayList<String>();
        paths.add("/");

        int index = 1;
        StringBuilder currentPath = new StringBuilder();
        while (index<path.length()) {
            char c = path.charAt(index);
            if (c=='/') {
                String current = currentPath.toString();
                if (!current.equals(".")) {
                    if (current.equals("..")) {
                        if (paths.size()>1) {
                            paths.remove(paths.size()-1);
                        }                      
                    } else if (currentPath.length()>0) {
                        paths.add(current);
                    }
                }                 
                currentPath.setLength(0);
            } else {
                currentPath.append(c);
            }

            if (index==path.length()-1 && currentPath.length()>0) {
                String current = currentPath.toString();
                if (!current.equals(".")) {
                    if (current.equals("..")) {
                        if (paths.size()>1) {
                            paths.remove(paths.size()-1);
                        } 
                    } else {
                        paths.add(current);
                    } 
                }                             
            }
            index = index + 1;
        }

        currentPath.setLength(0);

        for (int i=0; i<paths.size(); i++) {
            currentPath.append(paths.get(i));
            if (i<paths.size()-1 && !currentPath.toString().equals("/")) {
                currentPath.append("/");
            }
        }

        return currentPath.toString();
    }