388.文件的最长绝对路径
标答里的程序看了半天才懂,前后铺垫的一环扣一环,虽然奇妙,但也恶心到我了🤢
int lengthLongestPath(char * input){
int len=strlen(input),index=0,top=0;
int maxcount=0;
int*stack=(int*)malloc(sizeof(int)*len);记录文件(夹)的字符串长度
while(index<len){这里是一个字符一个字符扫描,但循环内部不一定
int depth=1;记录文件(夹)深度
while(input[index]=='\t'&&index<len){
depth++;
index++;
}
int count=0;每次需要重新计数新字符串
bool file=false;
while(input[index]!='\n'&&index<len){这里要有index<len,否则程序死循环,开始的字符满足条件,但后面连续的字符会不满足条件。
if(input[index]=='.'){
file=true;代表找到文件}
count++;
index++;}
index++;换行符跳过
while(top>=depth){
top--;
}当文件(夹)深度降低,必须使top=depth-1才能更新栈
if(top>0){
count+=(stack[top-1]+1);代表文件名长度的累加,1是每个文件名前的‘/’
}
if(file){
maxcount=fmax(maxcount,count);找到文件,一条路径结束,需更新栈(栈代表路径),走新路径会导致深度depth会<=原来的深度,一条路径走到最终文件前,必须要top=depth-1,比如一条路径最大depth为4,则其top为3,若下条路径初始值为2,代表从深度为2的文件开始就发生变化,需要栈从top=1处更新。
maxcount记录每条路径的最大长度
}else{
stack[top++]=count;}
}
return maxcount;}