[Leetcode] Simplify Path

Source: Internet
Author: User

Simplify Path

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 where path = "/../" ?
    In this case, you should return "/" .
  • Another corner case is the path might contain multiple slashes ‘/‘ together, such as "/home//foo/" .
    Should ignore redundant slashes and return "/home/foo" .

Problem Solving Ideas:

The path of simplification. Can be recorded with a stack. Traverse the original path and encounter/To determine the most recent word. If the "." Then do nothing. If "...", pop up the top element of the stack, otherwise into the stack.

One of the more ingenious ways is to add a slash directly behind the path, so you can avoid a slash or a slash behind the discussion.

Class Solution {public:    string Simplifypath (string path) {        stack<string> ss;        Path = path + "/";        int len = Path.length ();        String s= "";        for (int i=0; i<len; i++) {            if (path[i]== '/') {                if (s== ":") {                    if (!ss.empty ()) {                        ss.pop ();                    }                } else if (s!= "" &&s!= ".") {                    Ss.push (s);                }                S= "";            } else{                s=s+path[i];            }        }        while (!ss.empty ()) {            s = string ("/") + ss.top () + S;            Ss.pop ();        }        if (s== "") {            s= "/";        }        return s;    };


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

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