388. 文件的最长绝对路径
题目来源:388. 文件的最长绝对路径
2022.04.20 每日一题
LeetCode 题解持续更新中GitHub仓库地址 CSDN博客地址
今天的题目,题干不是很容易理解,但是理解题干以后就会好很多。
首先,题目的意思是想要找到最内层的文件夹中的文件的最长路径
给的字符串中有\n
有\t
,一看,啊太烦人了,乱七八糟的,整理后一看,会发现,还是拥有规律的,\n
说明在当前文件夹下有新的文件或者文件夹,\t
的个数代表了当前路径下的第层文件(夹),
我们就可以从 \n
开始下手,将字符串按照 \n
进行分割,然后统计分割后每个字符串中\t
的个数count
,然后在 lengthCount
数组中不断更新当前的值,lengthCount[count]
表示当前 在 第 count 层的文件路径的长度
然后判断当前字符串中是否包含.
字符,如果包含,说明当前路径是文件,就统计当前路径的长度,与当前的最大值进行比较取最大值,最后返回结果
class Solution {
public:
int lengthLongestPath(string input) {
// 首先将字符串按照 \n 进行分割
// 因为一个 \n 代表一级菜单
vector<string> split = split1(input, "\n");
// 创建一个数组,用于统计第 i 级菜单的长度
vector<int> lengthCount(10000);
// 定义一个结果变量
int res = 0;
for (int i = 0; i < split.size(); i++) {
// 判断当前处于第几级菜单
int count = countTab(split[i]);
// 当前菜单的长度等于前一级菜单的长度 + 当前字符串的长度 - \t 的个数
lengthCount[count + 1] = lengthCount[count] + split[i].length() - count;
// 如果当前字符串是文件的话,就统计当前路径的长度,
// 与结果变量 res 进行比较,取最大值
if (split[i].find(".") != string::npos) res = max(res, lengthCount[count + 1] + count);
}
return res;
}
// 统计 字符串 s 中有多少 的 "\t", "\t"的个数,代表了,他处于第几层
int countTab(string s) {
int cnt = 0;
while (cnt < s.length() && s[cnt] == '\t') cnt++;
return cnt;
}
vector<string> split1(const string &str, const string &delim) {
vector<string> res;
if ("" == str) return res;
//先将要切割的字符串从string类型转换为char*类型
char *strs = new char[str.length() + 1]; //不要忘了
strcpy(strs, str.c_str());
char *d = new char[delim.length() + 1];
strcpy(d, delim.c_str());
char *p = strtok(strs, d);
while (p) {
//分割得到的字符串转换为string类型
string s = p;
//存入结果数组
res.push_back(s);
p = strtok(NULL, d);
}
return res;
}
};
class Solution {
public int lengthLongestPath(String input) {
// 首先将字符串按照 \n 进行分割
// 因为一个 \n 代表一级菜单
String[] split = input.split("\n");
// 创建一个数组,用于统计第 i 级菜单的长度
int[] lengthCount = new int[10000];
// 定义一个结果变量
int res = 0;
for (int i = 0; i < split.length; i++) {
// 判断当前处于第几级菜单
int count = countTab(split[i]);
// 当前菜单的长度等于前一级菜单的长度 + 当前字符串的长度 - \t 的个数
lengthCount[count + 1] = lengthCount[count] + split[i].length() - count;
// 如果当前字符串是文件的话,就统计当前路径的长度,
// 与结果变量 res 进行比较,取最大值
if (split[i].contains(".")) res = Math.max(res, lengthCount[count + 1] + count);
}
return res;
}
// 统计 字符串 s 中有多少 的 "\t", "\t"的个数,代表了,他处于第几层
public int countTab(String s) {
int cnt = 0;
while (cnt < s.length() && s.charAt(cnt) == '\t') cnt++;
return cnt;
}
}