Skip to content

Commit a11fe71

Browse files
authoredApr 12, 2023
Create 0071-simplify-path.java
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"
1 parent 050c9c5 commit a11fe71

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
 

Diff for: ‎java/0071-simplify-path.java

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution {
2+
public String simplifyPath(String path) {
3+
Stack<String> stack = new Stack<>();
4+
StringBuilder curr = new StringBuilder();
5+
6+
String newPath = path + "/";
7+
8+
for(int i=0;i<newPath.length();i++) {
9+
char ch = newPath.charAt(i);
10+
11+
if(ch == '/') {
12+
if(curr.toString().equals("..")) {
13+
if(!stack.isEmpty()) {
14+
stack.pop();
15+
}
16+
} else if(!curr.isEmpty() && !curr.toString().equals(".")) {
17+
stack.push(curr.toString());
18+
}
19+
20+
curr = new StringBuilder();
21+
} else {
22+
curr.append(ch);
23+
}
24+
}
25+
26+
curr = new StringBuilder();
27+
28+
while(!stack.isEmpty()) {
29+
curr.insert(0, "/" + stack.pop());
30+
}
31+
32+
if(curr.length() == 0) {
33+
curr.append('/');
34+
}
35+
36+
return curr.toString();
37+
}
38+
}

0 commit comments

Comments
 (0)