-
Notifications
You must be signed in to change notification settings - Fork 4
/
LongestAbsoluteFilePath.java
47 lines (43 loc) · 1.23 KB
/
LongestAbsoluteFilePath.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
42
43
44
45
46
47
package com.dbc;
import java.util.ArrayDeque;
import java.util.Deque;
public class LongestAbsoluteFilePath {
public int lengthLongestPath(String input) {
int n = input.length();
int pos = 0;
int ans = 0;
Deque<Integer> stack = new ArrayDeque<Integer>();
while (pos < n) {
/* 检测当前文件的深度 */
int depth = 1;
while (pos < n && input.charAt(pos) == '\t') {
pos++;
depth++;
}
/* 统计当前文件名的长度 */
boolean isFile = false;
int len = 0;
while (pos < n && input.charAt(pos) != '\n') {
if (input.charAt(pos) == '.') {
isFile = true;
}
len++;
pos++;
}
/* 跳过当前的换行符 */
pos++;
while (stack.size() >= depth) {
stack.pop();
}
if (!stack.isEmpty()) {
len += stack.peek() + 1;
}
if (isFile) {
ans = Math.max(ans, len);
} else {
stack.push(len);
}
}
return ans;
}
}