2014年4月19日 星期六

[LeetCode] Simplify Path

Problem:
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".
Solution:O(n)
public class Solution {
   public String simplifyPath(String path) {
        String [] sets = path.split("/");
        Stack<String> stack = new Stack<String>();

        for(int i=0;i< sets.length; i++){
            if(sets[i].equals("") || sets[i].equals(".")){
                continue;
            }
            if(sets[i].equals("..")){
             if (!stack.isEmpty())
              stack.pop();
            }
            else{
            stack.add(sets[i]);
            }
        }
        String ret = "";
        while(!stack.isEmpty()){
            ret=  "/"+stack.pop() +ret;
        }
        if(ret.equals(""))
         ret = "/";
        return ret;
    }
}
Key Concept: Using Stack

沒有留言:

張貼留言