[leetcode]Simplify Path

来源:互联网 发布:淘宝直播如何找商家 编辑:程序博客网 时间:2024/04/29 04:00
class Solution {public:    string simplifyPath(string path) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(path.empty()) return "";                if(path[path.size()-1] != '/') path += "/";        int N = path.size();        stack<string> s;        string tmp;                for(int i = 0; i < N; i++){            if(path[i] == '/'){                if(tmp == ".."){                    if(!s.empty()) s.pop();                }else if(!tmp.empty() && tmp != "." && tmp != ".."){                    s.push(tmp);                }                tmp.clear();                    }else{                tmp += path[i];                            }        }                //reverse stack        stack<string> s1;        while(!s.empty()){            s1.push(s.top());            s.pop();        }                string result = "";        while(!s1.empty()){            result += "/";            result += s1.top();            s1.pop();        }                return result == "" ? "/" : result;            }};