leetcode[71]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/".
    In this case, you should ignore redundant slashes and return "/home/foo".
class Solution {

public:

string simplifyPath(string path) 

{

    if(path.empty())return path;

    stack<string> sta;

    string str="";

    for (int i=0;i<path.size();i++)

    {

        if (path[i]=='/')

        {

            if (str=="..")

            {

                if (!sta.empty())

                {

                    sta.pop();

                }

                str="";

            } 

            else if(str==".")

            {

                str="";

            }

            else if(str!="")

            {

                sta.push(str);

                str="";

            }

        } 

        else

        {

            str+=path[i];

        }

    }

    if (str=="..")

    {

        if (!sta.empty())

        {

            sta.pop();

        }

    }

    else if(str!="."&&str!="")

    {

        sta.push(str);

    }

    string res="";

    while(!sta.empty())

    {

        if (res=="") res=sta.top();

        else  res=sta.top()+"/"+res;

        sta.pop();

    }

    res="/"+res;

    return res;

}

/**

string simplifyPath(string path) 

{

    if (path.empty())return path;

    string str="";

    stack<string> stack1;

    for (int i=0;i<path.size();i++)

    {

        if (path[i]=='/')

        {

            if (str=="..")

            {

                if (!stack1.empty())

                {

                    stack1.pop();

                }

            }

            else if(str.size()!=0&&str!=".")

            {

                stack1.push(str);

            }

            str="";

        }

        else

        {

            str+=path[i];

        }

    }

    if (str=="..")

    {

        if (!stack1.empty())

        {

            stack1.pop();

        }

    }

    else if (str.size()!=0&&str!=".")

    {

        stack1.push(str);

    }

    string res="";

    while(!stack1.empty())

    {

         if(res.size()==0)res=stack1.top();

         else res=stack1.top()+'/'+res;

         stack1.pop();

    }

    res="/"+res;

    return res;

}

*/

};

 

你可能感兴趣的:(LeetCode)