File tree 1 file changed +26
-0
lines changed
solution/0071.Simplify Path
1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public String simplifyPath (String path ) {
3
+ List <String > dirs = new ArrayList <>();
4
+ int dirStart = 0 , len = path .length ();
5
+ while (dirStart < len ) {
6
+ while (dirStart < len && path .charAt (dirStart ) == '/' ) dirStart ++;
7
+ int dirEnd = dirStart ;
8
+ while (dirEnd < len && path .charAt (dirEnd ) != '/' ) dirEnd ++;
9
+ String dir = path .substring (dirStart , dirEnd );
10
+ if (!"." .equals (dir )) {
11
+ if (".." .equals (dir )) {
12
+ if (! dirs .isEmpty ()) dirs .remove (dirs .size () - 1 );
13
+ } else if (dir .length () > 0 ) {
14
+ dirs .add (dir );
15
+ }
16
+ }
17
+ dirStart = ++dirEnd ;
18
+ }
19
+ StringBuilder sb = new StringBuilder ("/" );
20
+ for (int i = 0 ; i < dirs .size (); i ++) {
21
+ if (i == dirs .size () - 1 ) sb .append (dirs .get (i ));
22
+ else sb .append (dirs .get (i )).append ("/" );
23
+ }
24
+ return sb .toString ();
25
+ }
26
+ }
You can’t perform that action at this time.
0 commit comments