Share my C++ solution, easy to understand


  • 1
    V
    class Solution {
    public:
        string simplifyPath(string path) {
            int i = 0;
            int len = path.length();
            
            string ret;
            vector<string> stack_path;
            
            while (i < len)
            {
                int j = i + 1;
                for (; j < len && path[j] != '/'; j++)
                    ;
                string sub = path.substr(i+1, j-i-1);
                
                if (sub.length() > 0)
                {
                    if (sub == "..")
                    {
                        if (stack_path.size() > 0)
                            stack_path.pop_back();
                    }
                    else if (sub != ".")
                        stack_path.push_back(sub);
                }
                
                i = j;
            }
            
            int cnt = stack_path.size();
            if (cnt == 0)
                return "/";
                
            for (i = 0; i < cnt; i++)
            {
                ret += "/";
                ret += stack_path[i];
            }
            
            return ret;
        }
    };
    

  • 0

    it's really straight forward! Thanks !


Log in to reply
 

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