1
+ /*
2
+ Author: Andy, nkuwjg@gmail.com
3
+ Date: Jan 11, 2015
4
+ Problem: Simplify Path
5
+ Difficulty: Easy
6
+ Source: https://oj.leetcode.com/problems/simplify-path/
7
+ Notes:
8
+ Given an absolute path for a file (Unix-style), simplify it.
9
+
10
+ For example,
11
+ path = "/home/", => "/home"
12
+ path = "/a/./b/../../c/", => "/c"
13
+
14
+ Corner Cases:
15
+ Did you consider the case where path = "/../"?
16
+ In this case, you should return "/".
17
+ Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
18
+ In this case, you should ignore redundant slashes and return "/home/foo".
19
+
20
+ Solution: Add an additional '/' at the end of 'path' for simply detecting the end.
21
+ */
22
+ public class Solution {
23
+ public String simplifyPath (String path ) {
24
+ if (path .length ()==0 )return "/" ;
25
+ if (path .charAt (0 )!='/' )return "/" ;
26
+ ArrayList <String >dirs =new ArrayList <String >();
27
+ String []str =path .split ("/" );
28
+ for (int i =0 ;i <str .length ; ++i ) {
29
+ if ((i ==0 ||i ==str .length -1 ) &&str [i ].compareTo ("" ) ==0 )continue ;
30
+ if (str [i ].compareTo (".." ) ==0 ) {
31
+ if (dirs .isEmpty () ==false ) {
32
+ dirs .remove (dirs .size () -1 );
33
+ }
34
+ }else if ((str [i ].compareTo ("." ) !=0 ) && (str [i ].compareTo ("" ) !=0 )) {
35
+ dirs .add (str [i ]);
36
+ }
37
+ }
38
+ if (dirs .isEmpty () ==true )return "/" ;
39
+ StringBuilder res =new StringBuilder ();
40
+ for (int i =0 ;i <dirs .size (); ++i ) {
41
+ res .append ("/" );
42
+ res .append (dirs .get (i ));
43
+ }
44
+ return res .toString ();
45
+ }
46
+ }