输入:input = “dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext”
输出:32
解释:存在两个文件:
“dir/subdir1/file1.ext” ,路径长度 21
“dir/subdir2/subsubdir2/file2.ext” ,路径长度 32
返回 32 ,因为这是最长的路径
用stringstream+getline以’\n’为分割符分割字符串为若干行。建立层次到其文件夹前缀的长度的映射。对特定的path根据里面是否含有’.'来判断是否是文件。
是文件的话用mp[level] + len有条件的更新最大长度,否则更新新文件夹及其长度到map表:mp[level+1] = mp[level] + len + 1,为可能的其下文件长度做准备。
class Solution {
public:
int lengthLongestPath(string input) {
stringstream ss(input);
vector<string> paths;
string path;
while(getline(ss,path,'\n')){
paths.push_back(path);
}
int res=0;
unordered_map<int,int>mp;
for(auto path : paths){
int level=path.find_last_of('\t')+1;
int len=path.substr(level).size();
if(path.find('.')!=string::npos){
res=max(res,mp[level]+len);
}else {
mp[level+1]=mp[level]+len+1;
}
}
return res;
}
};