Skip to content

Commit

Permalink
Create 0071-simplify-path.java
Browse files Browse the repository at this point in the history
Given a string path, which is an absolute path (starting with a slash '/') to a file or directory in a Unix-style file system, convert it to the simplified canonical path.

In a Unix-style file system, a period '.' refers to the current directory, a double period '..' refers to the directory up a level, and any multiple consecutive slashes (i.e. '//') are treated as a single slash '/'. For this problem, any other format of periods such as '...' are treated as file/directory names.

The canonical path should have the following format:

The path starts with a single slash '/'.
Any two directories are separated by a single slash '/'.
The path does not end with a trailing '/'.
The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period '.' or double period '..')
Return the simplified canonical path.

I/P   : ""/a//b////c/d//././/..""
O/P : "/a/b/c"
  • Loading branch information
sumit16sharma authored Apr 12, 2023
1 parent 050c9c5 commit a11fe71
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions java/0071-simplify-path.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
class Solution {
public String simplifyPath(String path) {
Stack<String> stack = new Stack<>();
StringBuilder curr = new StringBuilder();

String newPath = path + "/";

for(int i=0;i<newPath.length();i++) {
char ch = newPath.charAt(i);

if(ch == '/') {
if(curr.toString().equals("..")) {
if(!stack.isEmpty()) {
stack.pop();
}
} else if(!curr.isEmpty() && !curr.toString().equals(".")) {
stack.push(curr.toString());
}

curr = new StringBuilder();
} else {
curr.append(ch);
}
}

curr = new StringBuilder();

while(!stack.isEmpty()) {
curr.insert(0, "/" + stack.pop());
}

if(curr.length() == 0) {
curr.append('/');
}

return curr.toString();
}
}

0 comments on commit a11fe71

Please sign in to comment.