Tuesday, February 11, 2014

Simplify Path

Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
click to show corner cases.

Solution:
background:
Directory separator: "/"
Current Directory: "."
Parent Directory: ".."
Home Directory: "~"
/b/.. , ./ did nothing, so we can use a stack to get rid of such operations. 
public class Solution {
    public String simplifyPath(String path) {
        Stack stack = new Stack();
        String[] split = path.split("/");
        for(String s: split){
            if(s.equals(".") || s.equals("")) continue;
            if(s.equals("..")){
                if(!stack.isEmpty()){
                    stack.pop();
                }
            }
            else stack.push(s);
        }
        StringBuilder ret = new StringBuilder();
        while(!stack.isEmpty()){
            ret.insert(0, stack.pop());
            ret.insert(0, "/");
        }
        return ret.length() == 0 ? "/" : ret.toString();  // corner case: null
    }
}

No comments:

Post a Comment