1: class Solution {
2: public:
3: int lengthLongestPath(string input) {
4: int maxL = 0, l = 1, len = 0;
5: bool isFile = false;
6: vector<int> level(1, 0);
7: for (int i = 0; i < input.size(); i++) {
8: while (input[i] == '\t') {
9: l++, i++;
10: }
11: while (input[i] != '\n' && i < input.size()) {
12: if (input[i] == '.') isFile = true;
13: len++, i++;
14: }
15: if (isFile) {
16: maxL = max(maxL, level[l-1]+len);
17: } else {
18: if (l == level.size()) level.push_back(level[l-1]+len+1);
19: else level[l] = level[l-1] + len + 1;
20: }
21: len = 0, l = 1, isFile = false;
22: }
23: return maxL;
24: }
25: };
Thursday, October 6, 2016
388. Longest Absolute File Path
This problem has long long description and the file path is very confusing at the first glance. However, if you read the path carefully, you'll find that '\t' indicates the depth of a directory or file and '\n' indicates the end of the directory or file. Also you should notice that the file in the path appears one by one, so the solution becomes to have an array to store the length for each depth and once reaches a file, compute the total length to the file. After computing a file, everything can be reset to start finding a new file.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment