File tree 1 file changed +12
-25
lines changed
1 file changed +12
-25
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
2
public String simplifyPath (String path ) {
3
3
Stack <String > stack = new Stack <>();
4
- StringBuilder sb = new StringBuilder ();
5
- int idx = 0 ;
6
- int n = path .length ();
7
- while (idx < n ) {
8
- if (path .charAt (idx ) == '/' ) {
9
- idx ++;
10
- while (idx < n && path .charAt (idx ) != '/' ) {
11
- sb .append (path .charAt (idx ++));
12
- }
13
- String dir = sb .toString ();
14
- sb .setLength (0 );
15
- if (dir .equals (".." )) {
16
- if (!stack .isEmpty ()) {
17
- stack .pop ();
18
- }
19
- }
20
- else if (dir .equals ("." ) || dir .length () == 0 ) {
21
- continue ;
22
- }
23
- else {
24
- stack .push (dir );
4
+ String [] splits = path .split ("/" );
5
+ for (String split : splits ) {
6
+ if (split .equals ("" ) || split .equals ("." )) {
7
+ continue ;
8
+ } else if (split .equals (".." )) {
9
+ if (!stack .isEmpty ()) {
10
+ stack .pop ();
25
11
}
12
+ } else {
13
+ stack .push (split );
26
14
}
27
15
}
28
- sb = new StringBuilder ();
16
+ StringBuilder resultingPath = new StringBuilder ();
29
17
while (!stack .isEmpty ()) {
30
- sb .insert (0 , stack .pop ());
31
- sb .insert (0 , "/" );
18
+ resultingPath .insert (0 , stack .pop ()).insert (0 , "/" );
32
19
}
33
- return sb .length () > 0 ? sb .toString () : "/" ;
20
+ return resultingPath .length () == 0 ? "/" : resultingPath .toString ();
34
21
}
35
22
}
You can’t perform that action at this time.
0 commit comments