C++ concise 0ms solution


  • 0
    Z
    class Solution {
    public:
        int lengthLongestPath(string input) {
            if (input.empty()) return 0;
            input = "\n" + input + "\n";
            
            unordered_map<int, int> dp_map; // Record the length of the on processing file system path on each depth
            bool isFile = false;
            int i = 0, max = 0, depth = 0, cur = 0, len = input.length();
            while (i < len) {
                if (input[i] == '.') isFile = true;
                if (input[i] == '\n') {
                    if (isFile) {
                        int total = dp_map[depth - 1] + cur; // by default dp_map[-1] = 0
                        if (max < total) max = total;
                        isFile = false;
                    } else {
                        dp_map[depth] = dp_map[depth - 1] + cur + 1; // by default dp_map[-1] = 0
                    }
                    int td = 0; // calculate the depth for the followed dir or file in the sequence
                    while (input[++i] == '\t') ++td;
                    if (depth != td) depth = td;
                    cur = 0;
                }
                ++cur;
                ++i;
            }
            return max;
        }
    };
    

Log in to reply
 

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