wayetan
3/3/2014 - 2:30 AM

Simplify Path

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 class Solution {
    public String simplifyPath(String path) {
        if(path == null || path.length() == 0) 
            return "/";
        Stack<String> stack = new Stack<String>();
        String[] splits = path.trim().split("/");
        for(String s : splits) {
            if(s == null || s.length() == 0 || s.equals(".")) {
                // do nothing.
                continue;
            } else if (s.equals("..")) {
                // pop if stack is not empty;
                if (stack.size() > 0) 
                    stack.pop();
            } else {
                // push all others to stack
                stack.push(s);
            }
        }
        // stack can be empty.
        if(stack.isEmpty()) 
            return "/";
        StringBuffer buf = new StringBuffer();
        while(!stack.isEmpty()) {
            buf.insert(0, stack.pop());
            buf.insert(0, "/");
        }
        return buf.toString();
    }
}