[Leedcode 71] Simplify Path

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"

 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

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.