Easy to understand clean C++ code with comments

  • 1

    Use the C++ getline function to split the '\n'. Then count the number of '\t' to determine the level.

        int lengthLongestPath(string input) {
            vector<int> level(100, 0);
            int maxi=0;
            string cur;
            stringstream ss(input);
            while (getline(ss, cur, '\n')) {
                int cnt=0;
                // find # of '\t'
                size_t pos = cur.find_last_of('\t');
                if (pos==string::npos) cnt = 0;
                else cnt = pos+1;
                // record level or file size
                if (cur.find(".")==string::npos)
                    level[cnt+1] = level[cnt] + cur.size()-cnt;
                    maxi = max(maxi, (int)(level[cnt] + cur.size())); // cur.size() not minus cnt to compensate for the forward slash '/' in the return requirement
            return maxi;

  • 3

    you so diao!

  • 0

    Nice idea.
    However, this solution might fail if there are more than 100 levels.

Log in to reply

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