--- tags: leetcode --- # [388. Longest Absolute File Path](https://leetcode.com/problems/longest-absolute-file-path/) --- # My Solution ## The Key Idea for Solving This Coding Question ## C++ Code ```cpp= struct pathData { int pathLen; int level; pathData(int pathLen, int level) : pathLen(pathLen), level(level) {} }; class Solution { public: int lengthLongestPath(string input) { int i = 0; int longestLen = 0; stack<pathData> st; while (i < input.size()) { if (input[i] == '\n') { ++i; } int level = 0; while (i < input.size() && input[i] == '\t') { ++level; ++i; } int nameLen = 0; bool isFile = false; while (i < input.size() && input[i] != '\n') { if (input[i] == '.') { isFile = true; } ++nameLen; ++i; } if (!isFile) { ++nameLen; // append the '/' for directory. } while (!st.empty() && st.top().level >= level) { st.pop(); } if (st.empty()) { st.push(pathData(nameLen, level)); } else { st.push(pathData(st.top().pathLen + nameLen, level)); } if (isFile && longestLen < st.top().pathLen) { longestLen = st.top().pathLen; } } return longestLen; } }; ``` ## Time complexity $O(n)$ $n$ is the length of `path`. ## Space complexity $O(L)$ $L$ is the level of the filesystem hierarchy. # Miscellane <!-- # Test Cases ``` "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" ``` ``` "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext" ``` ``` "a" ``` ``` "file1.txt\nfile2.txt\nlongfile.txt" ``` -->
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up