题目
考查如何保存上一次的结果方法一:递归,方法二:数组,或者栈
//我刚开始的思想是直接对其进行'\t'分割,递归之后对于'\t\t'分割,
// 但是发现,第一次递归对于'\t'分割,已经不能行的通了。
//既然递归行不通,可以借助栈,采取手动解析的方式。
//如何判断下一个节点是栈顶元素的下一个目录节点?采用深度来判断。每个'\t'代表一个深度。
//其实这道题就是考查,如何记录已经遍历过的节点,方法一:递归,方法二:数组,或者栈
public int lengthLongestPath(String input) {
int length = input.length();
int pos = 0;
int ans = 0;
Deque<Integer> stack = new LinkedList<>();
//根目录拥有多个目录情况下。
while (pos < length) {
int depth = 1;
//计算当前节点深度
while (pos < length && input.charAt(pos) == '\t') {
pos++;
depth++;
}
//计算当前节点长度
int len = 0;
//计算是否为文件
boolean isFile = false;
while (pos < length && input.charAt(pos) != '\n') {
if (input.charAt(pos) == '.') {
isFile = true;
}
pos++;
len++;
}
// 跳过当前的换行符
pos++;
while (stack.size() >= depth) {
stack.pop();
}
if (!stack.isEmpty()) {
// + 1就是绝对位置的/需要加进去
len += stack.peek() + 1;
}
if (isFile) {
ans = Math.max(ans, len);
} else {
stack.push(len);
}
}
return ans;
}
//同样,我们可以使用数组代替栈
class Solution {
public int lengthLongestPath(String input) {
int n = input.length();
int pos = 0;
int ans = 0;
int[] level = new int[n + 1];
while (pos < n) {
/* 检测当前文件的深度 */
int depth = 1;
while (pos < n && input.charAt(pos) == '\t') {
pos++;
depth++;
}
/* 统计当前文件名的长度 */
int len = 0;
boolean isFile = false;
while (pos < n && input.charAt(pos) != '\n') {
if (input.charAt(pos) == '.') {
isFile = true;
}
len++;
pos++;
}
/* 跳过换行符 */
pos++;
if (depth > 1) {
len += level[depth - 1] + 1;
}
if (isFile) {
ans = Math.max(ans, len);
} else {
level[depth] = len;
}
}
return ans;
}
}