2014年12月2日星期二

[Leetcode] Simplify Path

Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
Use split to split the path according to "/+". Then swap the entire array and maintain a stack. We do the following:
  1. If we encounter a ""(this might happen due to the first character of the path is "/") or a ".", we continue.
  2. If we encounter a "..", if there are something in the stack, we pop one out.
  3. Otherwise we push the string into the stack.
Finally, we append what in the stack together. Pay attention that when the stack is empty, we should return "/".

    public String simplifyPath(String path) {
        int n = path.length();
        if(n == 0)
            return "/";
        String[] strs = path.split("/+");
        List<String> stack = new ArrayList<String>();
        for(int i = 1; i < strs.length; i++) {
            if(strs[i].equals("."))
                continue;
            else if(strs[i].equals("..")) {
                if(stack.size() != 0)
                    stack.remove(stack.size() - 1);
            }
            else
                stack.add(strs[i]);
        }
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < stack.size(); i++) {
            sb.append("/");
            sb.append(stack.get(i));
        }
        if(stack.size() == 0) // corner case, if the stack is empty, should return "/" not ""
            return "/";
        return sb.toString();
     }

没有评论:

发表评论