首页 » 编程之美 » 正文

[leetcode_71]Simplify Path

将输入路径简化了unix风格的路径。栈即可解决。

class Solution {
public:
    string simplifyPath(string path) {
        vector&lt;char <em>&gt;paths;
        paths.clear();
        char * split = strtok(const_cast&lt;char</em>&gt;(path.c_str()),&quot;/&quot;);
        while(split != NULL) {
            paths.push_back(split);
            split = strtok(NULL,&quot;/&quot;);
        }
        stack&lt;char *&gt;st;
        for(int i = 0;i &lt; paths.size();i++) {
            if(strcmp(paths[i],&quot;.&quot;) == 0)continue;
            if(strcmp(paths[i],&quot;..&quot;) == 0) {
                if(!st.empty())st.pop();
            }
            else {
                st.push(paths[i]);
            }
        }
        paths.clear();
        while(!st.empty()) {
            paths.push_back(st.top());
            st.pop();
        }
        string spath = &quot;&quot;;
        for(int i = paths.size()-1;i &gt;= 0;i--) {
            spath = spath + string(&quot;/&quot;);
            spath = spath + string(paths[i]);
        }
        if(spath == &quot;&quot;)<br />
            spath = spath + string(&quot;/&quot;);
        return spath;
    }
};

发表评论