Thursday, January 8, 2015

LeetCode 71: Simplify Path

Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
public class Solution {
    public String simplifyPath(String path) {
        if (path.length() == 0)
            return path;
        
        Stack<String> stack = new Stack<>();
        
        // Split 'path' by "/"
        // e.g., path --- "/home//foo/", it will be splited as "home", "" and "foo".
        String[] list = path.split("/");
        
        for (int i = 0; i < list.length; i++)
        {
            // If "." or "", don't do anything.
            if (list[i].equals(".") || list[i].length()==0)
                continue;
            // If not "..", push string to stack.    
            else if (!list[i].equals(".."))
                stack.push(list[i]);
            // If ".." && stack isn't empty, pop stack. (".." means returning to parent directory)
            else if (!stack.isEmpty())
                stack.pop();
        }
        
        if (stack.isEmpty())
            return "/";
        
        String result = "";
        
        while (!stack.isEmpty())
        {
            result = stack.pop() + result;
            result = "/" + result;
        }
        
        return result;
    }
}

No comments:

Post a Comment