-
Notifications
You must be signed in to change notification settings - Fork 0
/
388LongestAbsoluteFilePath.js
95 lines (79 loc) · 2.16 KB
/
388LongestAbsoluteFilePath.js
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/**
* @param {string} input
* @return {number}
* @test: input = "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext"
*/
var lengthLongestPath = function(input) {
class Stack {
constructor() {
this.els = [];
}
pop() {
this.els.splice(this.els.length - 1, 1);
}
push(e) {
this.els.push(e);
}
top() {
return this.els[this.els.length - 1] || 0;
}
size() {
return this.els.length;
}
}
let counter = 0;
let fileFlag = false;
let level = 1;
let stack = new Stack();
let max = 0;
for (let i = 0; i < input.length; i++) {
let s = input.charAt(i);
if (s == "\n") {
let newLevel = calLevel(input, i);
if (newLevel > level) {
if (stack.size()) {
counter = stack.top() + counter;
}
stack.push(counter);
}
if (fileFlag) {
if (counter + level - 1 + stack.top() > max) {
max = counter + stack.top() + level - 1;
}
fileFlag = false;
}
while (newLevel <= level - 1) {
stack.pop();
level--;
}
level = newLevel;
counter = 0;
i = i - 1 + level;
} else {
if (s == '.') {
fileFlag = true;
}
counter++;
}
if(i == input.length - 1){
if (fileFlag) {
if (counter + level - 1 + stack.top() > max) {
max = counter + stack.top() + level - 1;
}
fileFlag = false;
}
}
}
function calLevel(input, i) {
if (input.charAt(i) != '\n') {
return;
}
let j = i + 1;
while (input.charAt(j) == "\t") {
j++;
}
return (j - i);
}
return max;
};
console.log(lengthLongestPath("dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext"));