Thursday, January 9, 2014

Leetcode: Simplify Path

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:

public class Solution {
    public String simplifyPath(String path) {
        String[] folders = path.split("/",-1);
        boolean[] used = new boolean[folders.length];
        for(int i=0; i<folders.length; i++)
        {
            if(folders[i].equals("."))
                used[i]=false;
            else if(folders[i].equals(".."))
            {
                used[i]=false;
                for(int j=i-1; j>=0; j--)
                    if(used[j])
                    {
                        used[j]=false;
                        break;
                    }
            }
            else if (folders[i].length()==0)
                used[i]=false;
            else
                used[i]=true;
        }
        StringBuilder sb = new StringBuilder();
        for(int i=0; i<folders.length; i++)
        {
            if(used[i])
            {
                sb.append('/');
                sb.append(folders[i]);
            }
        }
        if(sb.length()==0)
            sb.append('/');
        return sb.toString();
    }
}

No comments :

Post a Comment