Coding Saint - Simple Short Tutorials

Coding Saint - Simple Short Tutorials

Leetcode 71 Simplify Path (Medium)

Subscribe to my newsletter and never miss my upcoming articles

Question Link : https://leetcode.com/problems/simplify-path/

After reading the question , the first intution is for using stack as appropriate data structure There are two possiblities either you do interate character by character or split the string and find the all possible folder and insert in stack, we will follow the split based on "/" so that we get folders

Steps

  • split based on "/"
  • Possible Strings after split is "" (when multiple slashes are there), "folder name" ,"." and ".."
  • Interate over the array
    • if its a blank String igore and continue
    • now if current string is not "." or ".." it must be a folder name so add it to stack
    • if current String is ".." and stack is not empty the folder inside can be popped out as we need to go back one step
  • After iterating stack is empty return "/" or else create the folder structure by poping the element from stack
    public String simplifyPath(String path) {
          Stack<String> st= new Stack<>();
          StringBuffer sb= new StringBuffer();
          String paths[]=path.split("/");
          for(int i=0;i<paths.length;i++){
              String current=paths[i];
              if(current.equals(""))
                  continue;
              if( !current.equals(".") && !current.equals("..")){
                  st.push(current);
                  continue;
              }
              if(current.equals("..") && !st.isEmpty()){
                  st.pop();
              }
          }
          if (st.empty()){
              return "/";
          }
          String result="";
          while(!st.empty()){
              result = "/" + st.pop() + result;
          }
          return result;
      }
    
#algorithms#stack
 
Share this