71. Simplify Path

来源:互联网 发布:linux zip命令 密码 编辑:程序博客网 时间:2024/05/16 09:17

题目

Given an absolute path for a file (Unix-style), simplify it.

For example,
path = “/home/”, => “/home”
path = “/a/./b/../../c/”, => “/c”

思路

本题如果会用getline这个C++库函数,那么问题就简单了

代码

class Solution {public:    string simplifyPath(string path) {        string res, tmp;        vector<string> stk;        stringstream ss(path);        while(getline(ss,tmp,'/')) {            if (tmp == "" or tmp == ".") continue;            if (tmp == ".." and !stk.empty()) stk.pop_back();            else if (tmp != "..") stk.push_back(tmp);        }        for(auto str : stk) res += "/"+str;        return res.empty() ? "/" : res;}};