Two solutions using lists


  • 0

    Both solutions have the same idea, but the second one is shorter, cleaner and faster.

    Solution 1:

        public int LengthLongestPath(string input)
        {
            List<List<int>> levelPathCount = new List<List<int>>();
            int level = 0;
            string current = "";
            bool isCurrentStringFile = false;
            int max = 0;
            for (int i = 0; i < input.Length; i++)
            {
                if (i == input.Length-1 || input[i] == '\n')
                {
                    if (i == input.Length - 1) current += input[i];
                    if (level >= levelPathCount.Count) levelPathCount.Add(new List<int>());
                    int currentLength = (level == 0) ? current.Length : levelPathCount[level-1][levelPathCount[level-1].Count - 1] + current.Length+1;
                    if(isCurrentStringFile==true)
                        max = Math.Max(max, currentLength);
                    levelPathCount[level].Add(currentLength);
    
                    level = 0;
                    i += 1;
                    while (i<input.Length&&input[i] == '\t')
                    {
                        level++;
                        i += 1;
                    }
                    i--;
                    current = "";
                    isCurrentStringFile = false;
                }
                else
                {
                    current += input[i];
                    if (input[i] == '.')
                        isCurrentStringFile = true;
                }
            }
            return max;
        }
    

    Solution 2:

        public int LengthLongestPath(string input)
        {
            string[] dirs = input.Split('\n');
            List<int> levels = new List<int>();
            levels.Add(dirs[0].Length);
            int max = 0;
    
            for (int i = 0; i < dirs.Length; i++)
            {
                int level = FindLevel(dirs[i]);
                int currentLength =(level==0)?dirs[i].Length : levels[level - 1] + dirs[i].Length - level + 1;
                if (level >= levels.Count) levels.Add(currentLength);
                else levels[level] = currentLength;
                if(dirs[i].Contains('.'))
                {
                    max = Math.Max(max, currentLength);
                }
            }
            return max;
        }
            private int FindLevel(string s)
        {
            int level= 0;
            for (int i = 0; i <s.Length; i++)
            {
                if (s[i] == '\t') level++;
                else break;
            }
            return level;
        }
    

Log in to reply
 

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