File tree Expand file tree Collapse file tree 2 files changed +37
-0
lines changed
Expand file tree Collapse file tree 2 files changed +37
-0
lines changed Original file line number Diff line number Diff line change 1+ Given an absolute path for a file (Unix-style), simplify it.
2+
3+ For example,
4+ ** path** = "/home/", => "/home"
5+ ** path** = "/a/./b/../../c/", => "/c"
Original file line number Diff line number Diff line change 1+ public class Solution {
2+ public String simplifyPath (String path ) {
3+ if (path == null )
4+ return "/" ;
5+
6+ Stack <String > stack = new Stack <String >();
7+ stack .push ("/" );
8+
9+ String [] pathArray = path .split ("/" );
10+
11+ for (int i = 0 ; i < pathArray .length ; i ++) {
12+ if (pathArray [i ].equals ("." ) || pathArray [i ].equals ("" )) {
13+ //do nothing
14+ } else if (pathArray [i ].equals (".." )) {
15+ if (!stack .peek ().equals ("/" ))
16+ stack .pop ();
17+ } else {
18+ stack .push (pathArray [i ]);
19+ }
20+ }
21+
22+ StringBuilder sb = new StringBuilder ();
23+ for (String s : stack ) {
24+ sb .append (s );
25+ if (!s .equals ("/" ))
26+ sb .append ("/" );
27+ }
28+
29+ String result = sb .toString ();
30+ return result .length () > 1 ? result .substring (0 , result .length () - 1 ) : result ;
31+ }
32+ }
You can’t perform that action at this time.
0 commit comments