MCPcopy Create free account
hub / github.com/neetcode-gh/leetcode / simplifyPath

Method simplifyPath

java/0071-simplify-path.java:2–37  ·  view source on GitHub ↗
(String path)

Source from the content-addressed store, hash-verified

1class 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}

Callers

nothing calls this directly

Calls 6

equalsMethod · 0.80
toStringMethod · 0.45
isEmptyMethod · 0.45
popMethod · 0.45
pushMethod · 0.45
insertMethod · 0.45

Tested by

no test coverage detected