?LeetCode刷題實(shí)戰(zhàn)388:文件的最長(zhǎng)絕對(duì)路徑



示例
示例 1:
輸入:input = "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext"
輸出:20
解釋:只有一個(gè)文件,絕對(duì)路徑為 "dir/subdir2/file.ext" ,路徑長(zhǎng)度 20
路徑 "dir/subdir1" 不含任何文件
示例 2:
輸入:input = "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext"
輸出:32
解釋:存在兩個(gè)文件:
"dir/subdir1/file1.ext" ,路徑長(zhǎng)度 21
"dir/subdir2/subsubdir2/file2.ext" ,路徑長(zhǎng)度 32
返回 32 ,因?yàn)檫@是最長(zhǎng)的路徑
示例 3:
輸入:input = "a"
輸出:0
解釋:不存在任何文件
示例 4:
輸入:input = "file1.txt\nfile2.txt\nlongfile.txt"
輸出:12
解釋:根目錄下有 3 個(gè)文件。
因?yàn)楦夸浿腥魏螙|西的絕對(duì)路徑只是名稱本身,所以答案是 "longfile.txt" ,路徑長(zhǎng)度為 12
解題
class Solution {
public:
//獲取字符串中的一行,保存當(dāng)前行的終止位置在總字符串中的索引位置,‘\t’的數(shù)量和是否是文件名
int find_line(string&input,int pos,int& count_tab,bool& is_txt){
//初始化
count_tab=0;
is_txt=false;
//獲取一行
while(pos<input.size()){
if(input[pos]=='\t'){//記錄‘\t’的數(shù)量
++count_tab;
}
else if(input[pos]=='\n'){//找到當(dāng)前行的終止位置
break;
}
else if(input[pos]=='.'){//標(biāo)識(shí)是否是文件名字
is_txt=true;
}
++pos;
}
return pos;
}
int lengthLongestPath(string input) {
int pos=0;
vector<string> path;
int cur_len=0;//當(dāng)前路徑的長(zhǎng)度,不包括路徑名字之間的分隔符
int max_len=0;//最長(zhǎng)的路徑
int count_tab=0;//每行前面的'\t'的數(shù)量
bool is_txt=false;//當(dāng)前字符串名字是否是文件名
while(pos<input.size()){//遍歷字符串
//獲取當(dāng)前行
int cur_end=find_line(input,pos,count_tab,is_txt);
//獲取當(dāng)前行中的字符串名字
string cur_str=input.substr(pos+count_tab,cur_end-(pos+count_tab));
//根據(jù)‘\t’的數(shù)量,彈出多余的名字
while(path.size()>count_tab){
cur_len-=path.back().size();
path.pop_back();
}
//更新路徑長(zhǎng)度和路徑
cur_len+=cur_str.size();
path.push_back(cur_str);
if(is_txt){//更新可能的最大長(zhǎng)度
max_len=max_len>=cur_len+path.size()-1?max_len:cur_len+path.size()-1;
}
//更新索引位置,去獲取下一行
pos=cur_end;
if(pos!=input.size()){
++pos;
}
}
return max_len;
}
};
LeetCode1-380題匯總,希望對(duì)你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)381:O(1) 時(shí)間插入、刪除和獲取隨機(jī)元素
LeetCode刷題實(shí)戰(zhàn)382:鏈表隨機(jī)節(jié)點(diǎn)
LeetCode刷題實(shí)戰(zhàn)383:贖金信
LeetCode刷題實(shí)戰(zhàn)384:打亂數(shù)組
LeetCode刷題實(shí)戰(zhàn)385:迷你語(yǔ)法分析器
