[Leetcode] 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"

Click to show corner cases.

Corner cases:

 

  • Did you consider the case wherePath="/../"?
    In this case, you shoshould return"/".
  • Another corner case is the path might contain multiple slashes‘/‘Together, such"/home//foo/".
    In this case, you shoshould ignore redundant slashes and return"/home/foo".
Solution: Evaluate the Java string split function.
  1. Use/to split string
  2. Then let's take a look at each short section. If it is "." or "" (indicating two/connected), it will not go into the stack; if it is "...", pop; if it is normal, push.
 
 1 public class Solution { 2     public String simplifyPath(String path) { 3         if(path==null||path.length()==0) 4             return ""; 5         if(path.equals("/")) 6             return "/"; 7         String[] tokens=path.split("/"); 8         Stack<String> stack=new Stack<String>(); 9         10         for(int i=0;i<tokens.length;++i){11             if(tokens[i].equals("..")){12                 if(!stack.empty())13                     stack.pop();14                 else15                     continue;16             }else if(tokens[i].equals(".")||tokens[i].length()==0){17                 continue;18             }else{19                 stack.push(tokens[i]);20             }21         }22         23         Stack<String> stack2=new Stack<String>();24         String result=new String("");25         26         if(stack.empty())27             return "/";28         29         while(!stack.empty())30             stack2.push(stack.pop());31         while(!stack2.empty()){32             result+="/";33             result+=stack2.pop();34         }35         return result;   36     }37 }

 

[Leetcode] 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.