-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSimplifyPath.java
36 lines (30 loc) · 928 Bytes
/
SimplifyPath.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.smlnskgmail.jaman.leetcodejava.medium;
import java.util.Stack;
// https://leetcode.com/problems/simplify-path/
public class SimplifyPath {
private final String input;
public SimplifyPath(String input) {
this.input = input;
}
public String solution() {
Stack<String> stack = new Stack<>();
String[] s = input.split("/");
for (String str : s) {
if (str.equals("..")) {
if (!stack.isEmpty()) {
stack.pop();
}
} else if (!str.equals(".") && !str.equals("") && !str.equals(" ")) {
stack.push("/" + str);
}
}
if (stack.isEmpty()) {
return "/";
}
StringBuilder result = new StringBuilder();
while (!stack.isEmpty()) {
result.insert(0, stack.pop());
}
return result.toString();
}
}