Saturday, July 4, 2015

Simplify Path

Medium Simplify Path

22%
Accepted
Given an absolute path for a file (Unix-style), simplify it.
Have you met this question in a real interview? 
Yes
Example
"/home/", => "/home"
"/a/./b/../../c/", => "/c"
Challenge
  • 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 {
    /**
     * @param path the original path
     * @return the simplified path
     */
    public String simplifyPath(String path) {
        // Write your code here
        if(path == null || path.length() == 0) return path;
        Stack<String> stack = new Stack<String>();
        String[] arr = path.split("/");
        for(int i = 0; i < arr.length; i++){
            if(arr[i].equals( "..")){
                if(!stack.isEmpty()) stack.pop();
            } else if(!arr[i].equals(".") && !arr[i].isEmpty())
                        stack.push(arr[i]);
            
        }
        String res = "";
        while(!stack.isEmpty()){
            res = "/" + stack.pop() + res;
        }
        if(res.isEmpty()) return "/";
        return res;
    }
}

No comments:

Post a Comment