Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, = ="/home"
path = "/a/./b/../../c/"
, = ="/c"
Click to show corner cases.
Solution:
1 Public classSolution {2 Publicstring Simplifypath (string path) {3 if(Path.isempty ())return"";4 5StringBuilder Builder =NewStringBuilder ();6Builder.append ('/');7 intindex = 1;8 while(index<path.length ()) {9 //get the Next Directory command.Ten intNext =index; One while(Next<path.length () && Path.charat (next)! = '/') next++; AString dir =path.substring (index,next); - if(Dir.equals (".") | |Dir.isempty ()) { -index = next+1; the Continue; -}Else if(Dir.equals (".."))){ - Pathback (builder); -}Else { + Builder.append (dir); -Builder.append ('/'); + } Aindex = next+1; at } - - if(Builder.length () >1 && Builder.charat (Builder.length ()-1) = = '/') -Builder.deletecharat (Builder.length ()-1); - returnbuilder.tostring (); - } in - Public voidpathback (StringBuilder builder) { toBuilder.deletecharat (Builder.length ()-1); + while(Builder.length () >0 && Builder.charat (Builder.length ()-1)! = '/') -Builder.deletecharat (Builder.length ()-1); the if(Builder.length () ==0) builder.append ('/'); * } $}
Leetcode-simplify Path