LeetCode – Simplify Path (Java)

Given an absolute path for a file (Unix-style), simplify it.

For example,

path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
path = "/../", => "/"
path = "/home//foo/", => "/home/foo"

Java Solution

public String simplifyPath(String path) {
    Stack<String> stack = new Stack<String>();
 
    //stack.push(path.substring(0,1));
 
    while(path.length()> 0 && path.charAt(path.length()-1) =='/'){
        path = path.substring(0, path.length()-1);
    }
 
    int start = 0;
    for(int i=1; i<path.length(); i++){
        if(path.charAt(i) == '/'){
            stack.push(path.substring(start, i));
            start = i;
        }else if(i==path.length()-1){
            stack.push(path.substring(start));
        }
    }
 
    LinkedList<String> result = new LinkedList<String>();
    int back = 0;
    while(!stack.isEmpty()){
        String top = stack.pop();
 
        if(top.equals("/.") || top.equals("/")){
            //nothing
        }else if(top.equals("/..")){
            back++;
        }else{
            if(back > 0){
                back--;
            }else{
                result.push(top);
            }
        }
    }
 
    //if empty, return "/"
    if(result.isEmpty()){
        return "/";
    }
 
    StringBuilder sb = new StringBuilder();
    while(!result.isEmpty()){
        String s = result.pop();
        sb.append(s);
    }
 
    return sb.toString();
}
Category >> Algorithms >> Interview  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • FS

    Actually, I believe there is an error in this solution for the input case of “./../home” it will return “/home” instead of “home” or “./home”. I haven’t thought about the fix though 😉

  • Thire

    But “..” should not be ignored…
    You have to go back one level.

    “./a/b/c/../../d” == “./a/d”

  • NEWLIGHT

    This is handled by item.contains(“.”) as “..” contains a “.” inside of it. Therefore it will be ignored.

  • Thire

    what about “..” ?

  • NEWLIGHT

    Here is a solution that is much more efficient that I thought of in a couple of minutes.

    public static String simplifyPath(String path){

    String[] array = path.split(“/”);

    StringBuilder builder = new StringBuilder();

    for(String item : array){

    if(!item.contains(“.”) && !item.isEmpty()){

    builder.append(“/”);

    builder.append(item);

    }

    }
    return builder.toString();
    }