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


  • 0
    D

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

        //Base case: if path is empty return ""
        if(path==null || path.length()==0)
            return "";
            
        //array to store all the directories in the path
        String[] directories=path.split("/");
        
        //stringbuilder to store answer
        StringBuilder answer=new StringBuilder();
        
        //append the / in the beginninf
        answer.append("/");
        
        for(int i=0;i<directories.length;i++)
        {
            //if directory is current or null, continue
            if(directories[i].equals("") || directories[i].equals("."))
                continue;
            else if(directories[i].equals(".."))
            {
                //only if you are within another directory traverse back
                if(answer.length()>1)
                {
                    int j=answer.length()-2;
                    
                    while(answer.charAt(j)!='/')
                        j--;
                    
                    answer=answer.delete(j+1,answer.length());
                    
                }
                else
                    continue;
            }
            else
            {
                //append the directory along with a /
                answer.append(directories[i]);
                answer.append("/");
            }
        }
        
        //remove the last / only if your answer has more than length 1
        if(answer.length()>1)
            answer.deleteCharAt(answer.length()-1);
        
        
        return answer.toString();
        
    }
    

    }


Log in to reply
 

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