LintCode-简化路径

给定一个文档(Unix-style)的完全路径,请进行路径简化。

您在真实的面试中是否遇到过这个题?  Yes
样例

"/home/", => "/home"

"/a/./b/../../c/", => "/c"

挑战

  • 你是否考虑了 路径 = "/../" 的情况?

    在这种情况下,你需返回"/"

  • 此外,路径中也可能包含双斜杠'/',如 "/home//foo/"

    在这种情况下,可忽略多余的斜杠,返回 "/home/foo"

标签 
Expand  

分析:这题就是考栈的使用。。。

代码:

class Solution {
public:
    /**
     * @param path the original path
     * @return the simplified path
     */
    string simplifyPath(string& path) {
        // Write your code here
        stack<string> st;
        string cur = "";
        path+="/";
        for(int i=0;i<path.length();i++)
        {
            if(path[i]=='/')
            {
                if(cur=="..")
                {
                    if(!st.empty())
                        st.pop();
                }
                else if(cur=="."){}
                else if(cur.length()>0)
                {
                    st.push(cur);
                }
                cur = "";
            }
            else
                cur+=path[i];
        }
        string ret = "";
        while(!st.empty())
        {
            ret = "/"+st.top()+ret;
            st.pop();
        }
        if(ret.length()==0)
            ret = "/";
        return ret;
    }
};
    原文作者:LintCode题目解答
    原文地址: https://blog.csdn.net/wangyuquanliuli/article/details/46627819
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞