Easy java solution with comments(beats 45% of solutions)


  • 0
    D

    public class Solution {
    public String simplifyPath(String path) {

        //Base case: if path is null or empty, return string
        if(path==null || path.length()==0)
        {
            return "";
        }
        
        //store the different parts of the path in an array
        String[] directories=path.split("/");
        
        //variable to store the answer
        StringBuilder result=new StringBuilder("/");
        
        //traverse the array which has the directories
        for(int i=0;i<directories.length;i++)
        {
            //if directory is .., move back
            if(directories[i].equals(".."))
            {
                if(result.toString().equals("/"))
                {
                        continue;
                }
                else
                {
                   result.deleteCharAt(result.length()-1);
                   
                   int lastIndex=result.lastIndexOf("/");
                   
                   result.delete(lastIndex+1,result.length());
                   
                }
            }
            //skip the directory if it is empty or .
            else if(directories[i].equals(".") || directories[i].equals(""))
                continue;
            else
            {
                //append the current directory to the result
                result.append(directories[i]+"/");
            }
        }
        
        //delete the last / appended to the result
        if(result.toString().length()>1)
            result.deleteCharAt(result.length()-1);
        //return the answer
        return result.toString();
        
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.