-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy path_388.java
41 lines (37 loc) · 1.24 KB
/
_388.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* LeetCode 388 - Longest Absolute File Path
*
* Using a Stack
*/
public class _388 {
public int lengthLongestPath(String input) {
if (!input.endsWith("\n")) input = input + "\n";
char[] s = input.toCharArray();
int n = s.length;
int[] sLen = new int[n];
int[] sLevel = new int[n]; // in fact, we can even drop this array and use top-point instead
int top = 0, ptr = 0, ans = 0;
sLen[top] = -1; // since there is no leading / for an absolute path
sLevel[top++] = -1;
while (ptr < input.length()) {
int currentLevel = 0;
while (ptr < s.length && s[ptr] == '\t') {
currentLevel++;
ptr++;
}
int currentLen = 0;
boolean isFile = false;
while (s[ptr] != '\n') {
currentLen++;
isFile = isFile || s[ptr] == '.';
ptr++;
}
ptr++; // skip \n
while (top > 0 && sLevel[top - 1] >= currentLevel) top--;
sLen[top] = sLen[top - 1] + currentLen + 1; // + 1 for /
sLevel[top++] = currentLevel;
if (isFile) ans = Math.max(ans, sLen[top - 1]);
}
return ans;
}
}