10lines. Easy to understand, Java Solution, With Explanation


  • 0
    M

    Steps:

    1. Split the given input string with "/".

    2. Use stack to store the directory name.

    3. Skip if string length is zero, it handles the case of "//"

    4. Skip "." it does not change the directory structure in anyways

    5. If ".." then move back to previous directory by removing the top element in the stack.

    6. Otherwise store the directory name at the top of stack

    7. Now insert all the directory to a string and as it is stack, we should save the new directory name at the front.

      String[] op = path.split("/");
      Stack<String> folder = new Stack<String>();
      for(int i = 0 ; i < op.length; i++) {
      if((op[i].length() < 1) || op[i].equals(".")) continue;
      if(op[i].equals("..")) {if(! folder.empty()) folder.pop();}
      else folder.push(op[i]);
      }
      StringBuilder res = new StringBuilder();
      while(! folder.empty()) res.insert(0, "/" + folder.pop());
      return res.length() == 0 ? "/" : res.toString();


Log in to reply
 

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