Given an absolute path for a file (Unix-style), simplify it.
For example,
Path = "/home/" , = ="/home"
Path = "/a/./b/../../c/" , = ="/c"
Public classSolution { Publicstring Simplifypath (string path) {/*This topic is one of the more common operations in the Linux kernel, which simplifies the path of an input file. The idea is more clear, is to maintain a stack, for each block (with '/' as the demarcation) for analysis, if encountered '. /' means to go up a layer, that is to do the stack operation, if encountered './' is the current, skip directly, the other file path directly into the stack. Finally, the content of the stack is converted to a path. There will be no more than two scans in time (one is to get a simplified path to the stack, one to get the final result from the stack), so the time complexity is O (n), the size of the stack, and O (n). */Stack<String> stack=NewStack<string>(); intStart=0; for(intI=0;i<=path.length (); i++) {//Note the range of I. For this input "/home", you need to read to the last one, so I can be Len if(I<path.length () &&path.charat (i)! = '/') {Continue;} if(Start<i) {//pay attention to judgmentString temp=path.substring (start,i); if(Temp.equals (".."))){ if(!stack.empty ())//be careful to judge, not empty to ejectStack.pop (); }Else{ if(Temp.equals (".") ) {Start=i+1;//Note Update start to the next non-/' index Continue; } Else{Stack.push (temp); }}} start=i+1; } StringBuilder Res=NewStringBuilder (); if(Stack.empty ()) Res.append ("/");//Take into account the case of empty stack while(!Stack.empty ()) {String temp=Stack.pop (); Res.insert (0, "/" +temp);//Head Plug } returnres.tostring (); }}
[Leedcode 71] Simplify Path