71. Simplify Path
https://leetcode.com/problems/simplify-path/description/
Given an absolute path for a file (Unix-style), simplify it.
For example, path=
"/home/", =>"/home"path="/a/./b/../../c/", =>"/c"
Thoughts
压缩Unix路径:遇到.跳过,遇到..把上一个退出来。把上一个退出来用stack。
Code
/*
 * @lc app=leetcode id=71 lang=cpp
 *
 * [71] Simplify Path
 */
// @lc code=start
class Solution {
public:
    string simplifyPath(string path) {
        vector<string> s;
        stringstream ss(path);
        string tmp;
        while(getline(ss, tmp, '/')) {
            if (tmp == "" || tmp == ".") continue;
            if (tmp == ".." && !s.empty()) s.pop_back();
            else if (tmp != "..") s.push_back(tmp);
        }
        tmp.clear();
        for (const auto i : s) tmp += "/" + i;
        return tmp.empty() ? "/" : tmp;
    }
};
// @lc code=end
Last updated
Was this helpful?