A C++ solution used stack


  • 0

    There are 4 cases:
    Case 1: When there is repeated '/', ignore repeated '/'.
    Case 2: When come to /./, ignore it.
    Case 3: When come to '..', and stack is not empty, pop out stack.
    Other case: Push the stack.
    ·If return string is empty, return "/".

    string simplifyPath(string path) 
    {
    	stack<string> st;
    	string t = "";
    	for (int i = 0; i <= path.size(); ++i)
    	{
    		if (path.size() == i || '/' == path[i])
    		{
    			if (!t.empty() && "." != t && ".." != t) //Do not push "" into stack.
    				st.push(t);
    			else if (".." == t && !st.empty())
    				st.pop();
    			t.clear();
    			continue;
    		}
    		t.push_back(path[i]);
    	}
    	if (st.empty())
    		return "/";
    	string ret = "";
    	while (!st.empty())
    	{
    		ret = "/" + st.top() + ret;
    		st.pop();
    	}
    	return ret;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.