Leetcode 71 Solution

This article provides solution to leetcode question 71 (simplify-path)

https://leetcode.com/problems/simplify-path

Solution

class Solution { public: string simplifyPath(string path) { stack<string> s;
int i = 1; while (true) { int next_pos = path.find_first_of('/', i); auto file = next_pos == string::npos ? path.substr(i) : path.substr(i, next_pos - i);
if (file == "..") { if (s.empty() == false) s.pop(); } else if (file != "" && file != ".") s.push(file);
if (next_pos == string::npos) break;
i = next_pos + 1; }
string res; while (s.empty() == false) { res = "/" + s.top() + res; s.pop(); }
return res.size() == 0 ? "/" : res; } };