Monday, September 7, 2020

Facebook Question: Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.

Problem: Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.

In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period .. moves the directory up a level.

Note that the returned canonical path must always begin with a slash /, and there must be only a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /. Also, the canonical path must be the shortest string representing the absolute path.


Approach: Use stack.


        public static string SimplifyPath(string path)

        {

            Stack<string> stack = new Stack<string>();

            string[] arr = path.Split('/');

            foreach(string str in arr)

            {

                if (string.IsNullOrWhiteSpace(str) || str == ".")

                {

                    continue;

                }

                else if (str == "..")

                {

                    if (stack.Count == 0)

                    {

                        continue;

                    }

                    stack.Pop();

                }

                else

                {

                    stack.Push(str);

                }

            }

            if (stack.Count == 0)

            {

                return "/";

            }

            string[] result = new string[stack.Count * 2];

            int writeIndex = result.Length - 1;

            while(stack.Count > 0)

            {

                result[writeIndex--] = stack.Pop();

                result[writeIndex--] = "/";

            }

            return string.Join("", result);

        }



No comments:

Post a Comment