Given an absolute path for a file (Unix-style), simplify it.
For example,
Path = "/home/"
, = ="/home"
Path = "/a/./b/../../c/"
, = ="/c"
Use a stack to solve the problem. Encounter ' ... ' Stack, encounter '. ' Do not operate, other cases of pressure stack.
Code One:
classSolution: # @param path, astring# @return Astringdef simplifypath (self, path): Stack=[] I=0Res="' whilei<len (path): End= i+1 whileEnd<len (path) and path[end]! ="/": End+=1Sub= path[i+1: end]ifLen (sub) >0: ifSub = ="..": ifStack! =[]: Stack.pop () elif Sub!=".": Stack.append (sub) I=Endifstack = = []: return "/" forIinchStack:res+="/"+IreturnRes
Code 2:
classSolution:defSimplifypath (Self,path): Path= Path.split ('/') Res='/' forIinchPath:ifi = ='..': ifRes! ='/': Res='/'. Join (Res.split ('/') [:-1]) ifres = ="': res ='/' elifI! ='.' andI! ="': Res+='/'+iifRes! ='/' ElseIreturnRes
Turn from (reference):
1. http://www.cnblogs.com/zuoyuan/p/3777289.html
2. http://blog.csdn.net/linhuanmars/article/details/23972563
@ JAVA Version
Public string Simplifypath (string path) {if(Path = = NULL | | path.length () = =0) {return ""; } LinkedList<String> stack = new linkedlist<string>(); StringBuilder Res=new StringBuilder (); int i=R; while(i<path.length ()) {int index=i; StringBuilder Temp=new StringBuilder (); while(I<path.length () && Path.charat (i)! ='/') {temp.append (Path.charat (i)); I++; } if(index!=i) {String str=temp.tostring (); if(Str.equals ("..")) { if(!stack.isempty ()) Stack.pop (); } Else if(!str.equals (".") ) {Stack.push (str); }} I++; } if(!stack.isempty ()) {string[] STRs=Stack.toarray (New String[stack.size ()]); for(int j=strs.length-1;j>=0;j--) {res.append ("/"+Strs[j]); } } if(res.length () = =0)return "/"; returnres.tostring ();}
Leetcode's simplify Path @ python