Leetcode 388 Solution

This article provides solution to leetcode question 388 (longest-absolute-file-path)

https://leetcode.com/problems/longest-absolute-file-path

Solution

class Solution {
public:
    int lengthLongestPath(string input) {
        stack<int> s;
        int lastlen = 0;
        int curr_total = 0;
        int curr_max = 0;

        int i = 0;

        while (i < input.size())
        {
            int start = i;
            int layer = 0;
            int end = 0;
            bool isfile = false;
            int namesize = 0;

            for (int j = i; j < input.size(); j++)
            {
                if (input[j] == '\t')
                {
                    layer++;
                    continue;
                }
                else if (input[j] == '\n')
                {
                    end = j;
                    break;
                }
                else if (input[j] == '.')
                    isfile = true;

                namesize++;
            }

            if (end == 0)
                end = input.size();

            while (s.size() > layer)
            {
                curr_total -= s.top();
                s.pop();
            }

            if (isfile)
                curr_max = max(curr_max, (int)(curr_total + s.size() + namesize));
            else
                s.push(namesize), curr_total += namesize;

            i = end + 1;
        }

        return curr_max;
    }
};