Simple Solution using Stack in C#


  • 0
    P
    1. Split the given string on the basis of '/' and save the result in array

    2. Initialize a stack.

    3. Now, read the array items one by one.

    4. If the item is "..", pop item from stack and throw it away.

    5. If the item is ".", do nothing.

    6. Else, push it in the Stack.

    7. Finally, Pop items from the stack, one by one and keep adding them into a single string, separated by "/"

    public string SimplifyPath(string path)
            {
                string[] parts = path.Split('/');
                Stack<string> p = new Stack<string>();
    
                for (int i = 0; i < parts.Length; i++)
                {
                    string s = parts[i].Trim();
    
                    if (s == "..")
                    {
                        if (p.Count > 0)
                            p.Pop();
                    }
                    else if (s == ".")
                    { // do nothing.
                    }
                    else if (s.Length > 0)
                    {
                        p.Push(s);
                    }
                }
    
                string rtn = string.Empty;
    
                if (p.Count > 0)
                {
                    while (p.Count > 0)
                    {
                        rtn = "/" + p.Pop() + rtn;
                    }
    
                    return rtn;
                }
                else
                    return "/";
            }
    

Log in to reply
 

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