Leetcode's simplify Path @ python

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.