Cover image for Classic Interview 150 Questions P71 Simplify Path

Classic Interview 150 Questions P71 Simplify Path


Timeline

Timeline

2025-11-18

init

Stack

Problem:

We need to distinguish between the first “/” and the subsequent "/"s. The first is the root directory, while the subsequent ones are separators. Therefore, we can treat a directory as “/” + “directory name”.

If the directory is “”, i.e., an empty string, then it is the root directory.

123456789101112131415161718192021222324252627282930313233343536373839
#include <string>#include <stack>#include <sstream>using std::string;using std::stringstream;using std::stack;class Solution {    public:	string simplifyPath(string path)	{		string res, curr;		stringstream ss(path);		stack<string> st;		while (std::getline(ss, curr, '/')) {			if (curr.empty())				continue;			if (curr.compare("..") == 0) {				if (!st.empty())					st.pop();				else					continue;			} else if (curr.compare(".") == 0) {				continue;			} else {				st.push(curr);			}		}		while (!st.empty()) {			curr = st.top();			st.pop();			res.insert(0, curr);			res.insert(0, "/");		}		if (res.empty())			res = "/";				return res;	}};
Loading comments…