[LeetCode] 388. Longest Absolute File Path 最长的绝对文件路径
Suppose we abstract our file system by a string in the following manner:
The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents:
dir
subdir1
subdir2
file.ext
The directory dir contains an empty sub-directory subdir1 and a sub-directory subdir2 containing a file file.ext.
The string "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext" represents:
dir
subdir1
file1.ext
subsubdir1
subdir2
subsubdir2
file2.ext
The directory dir contains two sub-directories subdir1 and subdir2. subdir1 contains a file file1.ext and an empty second-level sub-directorysubsubdir1. subdir2 contains a second-level sub-directory subsubdir2 containing a file file2.ext.
We are interested in finding the longest (number of characters) absolute path to a file within our file system. For example, in the second example above, the longest absolute path is "dir/subdir2/subsubdir2/file2.ext", and its length is 32 (not including the double quotes).
Given a string representing the file system in the above format, return the length of the longest absolute path to file in the abstracted file system. If there is no file in the system, return 0.
Note:
- The name of a file contains at least a
.and an extension. - The name of a directory or sub-directory will not contain a
..
Time complexity required: O(n) where n is the size of the input string.
Notice that a/aa/aaa/file1.txt is not the longest file path, if there is another path aaaaaaaaaaaaaaaaaaaaa/sth.png.
解法1:栈Stack
一个字符串表示文件系统的目录结构,里面包含\n(回车)和\t(tab)的特殊字符,要找到最长的绝对文件路径。
可用栈Stack, Array, Hash table来保存每一层的最长路径长度。以栈为例:
1. 将字符串以'\n'进行拆分,得到目录字符串数组,设置最大长度变量 maxLen = 0,设置一个 Stack,初始设为0层为0。
2. 对这个数组迭代,对于每个目录字符串统计其前面的'\t'个数, 个数加1就是当前目录的层深度,比如: 0个'\t',层数就是1,1个'\t',层数是2。
3. 比较当前目录层数和栈顶层数:
1)如果目录层数大于栈顶层数:判断是否含'.' ,
a. 不含'.',则是目录,计算当前目录长度(字符长度+1因为要多1个"/")+ 上层目录最大长度,长度入栈。
b. 含'.' , 则为文件,计算当前文件长度(字符长度),此长度加上栈顶元素长度(上层目录最大长度)和maxLen比较取最大。
2)如果目录层数小于栈顶层数:
则弹出栈顶元素,用while循环,一直弹到栈顶的层小于当前层数。然后重复上面的a, b步骤
最后,返回maxLen.
解法2:哈希表HashMap
Java: Stack, Time: O(n), Space: O(n)
public class Solution {
public int lengthLongestPath(String input) {
String[] lines = input.split("\n");
Stack<Integer> path = new Stack<>();
path.push(0);
int max = 0;
for (String line : lines) {
int tabIndex = line.lastIndexOf("\t") + 1;
while (path.size() - 1 > tabIndex) {
path.pop();
}
int length = path.peek() + 1 + line.length() - tabIndex;
path.push(length);
if (line.indexOf(".") != -1)
max = Math.max(max, length - 1);
}
return max;
}
}
Java: DP Array, Time: O(n), Space: O(n)
public class Solution {
public int lengthLongestPath(String input) {
String[] lines = input.split("\n");
int[] length = new int[lines.length + 1];
int max = 0;
for (String line : lines) {
int depth = line.lastIndexOf("\t") + 1;
length[depth + 1] = length[depth] + 1 + line.length() - depth;
if (line.indexOf(".") != -1) {
max = Math.max(max, length[depth + 1] - 1);
}
}
return max;
}
}
Java: Stack
class Solution {
public int lengthLongestPath(String input) {
Deque<Integer> stack = new ArrayDeque<>();
stack.push(0); // "dummy" length
int maxLen = 0;
for(String s:input.split("\n")){
int lev = s.lastIndexOf("\t") + 1; // number of "\t"
while(lev + 1 < stack.size()) stack.pop(); // find parent
int len = stack.peek() + s.length() - lev + 1; // remove "/t", add"/"
stack.push(len);
// check if it is file
if(s.contains(".")) maxLen = Math.max(maxLen, len - 1);
}
return maxLen;
}
}
Java: Array instead of Stack
class Solution {
public int lengthLongestPath(String input) {
String[] paths = input.split("\n");
int[] stack = new int[paths.length+1];
int maxLen = 0;
for(String s:paths){
int lev = s.lastIndexOf("\t")+1, curLen = stack[lev+1] = stack[lev] + s.length() - lev + 1;
if(s.contains(".")) maxLen = Math.max(maxLen, curLen - 1);
}
return maxLen;
}
}
Python: HashMap
class Solution(object):
def lengthLongestPath(self, input):
"""
:type input: str
:rtype: int
"""
maxlen = 0
pathlen = {0: 0}
for line in input.splitlines():
name = line.lstrip('\t')
depth = len(line) - len(name)
if '.' in name:
maxlen = max(maxlen, pathlen[depth] + len(name))
else:
pathlen[depth + 1] = pathlen[depth] + len(name) + 1
return maxlen
Python: HashMap
class Solution(object):
def lengthLongestPath(self, input):
"""
:type input: str
:rtype: int
"""
def split_iter(s, tok):
start = 0
for i in xrange(len(s)):
if s[i] == tok:
yield s[start:i]
start = i + 1
yield s[start:] max_len = 0
path_len = {0: 0}
for line in split_iter(input, '\n'):
name = line.lstrip('\t')
depth = len(line) - len(name)
if '.' in name:
max_len = max(max_len, path_len[depth] + len(name))
else:
path_len[depth + 1] = path_len[depth] + len(name) + 1
return max_len
C++: Stack
class Solution {
public:
int lengthLongestPath(string input) {
input+= '\n';
int len = input.size(), ans = 0, spaceCnt = 0, curPathLen =0, dotFlag = 0;
stack<pair<string, int> > st;
string curDir, extension;
for(int i = 0; i < len; i++)
{
if(input[i]!='\n')
{
if(input[i]!='\t') curDir += input[i];
if(dotFlag) extension += input[i];
if(input[i]=='\t') spaceCnt++;
if(input[i]=='.') dotFlag = 1;
continue;
}
while(!st.empty() && spaceCnt <= st.top().second)
{
curPathLen -= st.top().first.size();
st.pop();
}
if(dotFlag) ans = max(curPathLen + (int)curDir.size() + 1, ans);
else
{
st.push(make_pair("/"+ curDir, spaceCnt));
curPathLen += curDir.size() + 1;
}
extension = "", dotFlag = 0, spaceCnt = 0, curDir = "";
}
return ans==0?0:ans-1;
}
};
All LeetCode Questions List 题目汇总
[LeetCode] 388. Longest Absolute File Path 最长的绝对文件路径的更多相关文章
- 388 Longest Absolute File Path 最长的绝对文件路径
详见:https://leetcode.com/problems/longest-absolute-file-path/description/ C++: class Solution { publi ...
- [LeetCode] Longest Absolute File Path 最长的绝对文件路径
Suppose we abstract our file system by a string in the following manner: The string "dir\n\tsub ...
- 【LeetCode】388. Longest Absolute File Path 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述: 题目大意 解题方法 日期 题目地址:https://leetcode. ...
- 【leetcode】388. Longest Absolute File Path
题目如下: Suppose we abstract our file system by a string in the following manner: The string "dir\ ...
- 388. Longest Absolute File Path
就是看哪个文件的绝对路径最长,不是看最深,是看最长,跟文件夹名,文件名都有关. \n表示一波,可能存在一个文件,可能只有文件夹,但是我们需要检测. 之后的\t表示层数. 思路是如果当前层数多余已经有的 ...
- leetcode 388.Lonest Absolute File Path
要求寻找的是最长的长度的,那么考虑文件夹和文件的存在的不同形式的,利用当前所存在的层数和对应的长度之间做一个映射关系的并且用于计算总的长度关系的. class Solution { public: i ...
- [Swift]LeetCode388. 文件的最长绝对路径 | Longest Absolute File Path
Suppose we abstract our file system by a string in the following manner: The string "dir\n\tsub ...
- Leetcode: Longest Absolute File Path
Suppose we abstract our file system by a string in the following manner: The string "dir\n\tsub ...
- Leetcode算法比赛----Longest Absolute File Path
问题描述 Suppose we abstract our file system by a string in the following manner: The string "dir\n ...
随机推荐
- django项目基于钩子验证的注册功能
前端html <div class="agile-row"> <h3>注册</h3> {# 注册的开始#} <div class=&quo ...
- gcc的__builtin_函数(注意前面是两个下划线)
说明: GCC provides a large number of built-in functions other than the ones mentioned above. Some of t ...
- Justice(HDU6557+2018年吉林站+二进制)
题目链接 传送门 题意 给你\(n\)个数,每个数表示\(\frac{1}{2^{a_i}}\),要你把这\(n\)个数分为两堆,使得每堆的和都大于等于\(\frac{1}{2}\). 思路 首先我们 ...
- python正则表达式练习题
# coding=utf-8 import re # 1. 写一个正则表达式,使其能同时识别下面所有的字符串:'bat','bit', 'but', 'hat', 'hit', 'hut' s =&q ...
- (转)接口测试工具Postman使用实践
一.接口定义 软件不同部分之间的交互接口.通常就是所谓的API――应用程序编程接口,其表现的形式是源代码. —— [ 百度百科 ]我们常说的接口一般指两种:(1)API:应用程序编程接口.程序间的接口 ...
- Classification and Decision Trees
分类和决策树(DT). 决策树是预测建模机器学习的一种重要算法. 决策树模型的表示是二叉树.就是算法和数据结构中的二叉树,没什么特别的.每个节点表示一个单独的输入变量(x)和该变量上的左右孩子(假设变 ...
- 2020年假期sql excel文件 获取
下载地址: https://files.cnblogs.com/files/shmily3929/2020.zip 说明:sql 不区分节假期和周六周末 excel文件区分节假日和周六周末
- WinDbg常用命令系列---单步执行p*
p (Step) p命令执行单个指令或源代码行,并可选地显示所有寄存器和标志的结果值.当子例程调用或中断发生时,它们被视为单个步骤. 用户模式: [~Thread] p[r] [= StartAddr ...
- 洛谷 P3380 【模板】二逼平衡树(树套树)-线段树套splay
P3380 [模板]二逼平衡树(树套树) 题目描述 您需要写一种数据结构(可参考题目标题),来维护一个有序数列,其中需要提供以下操作: 查询k在区间内的排名 查询区间内排名为k的值 修改某一位值上的数 ...
- gulp/webpack运行sass报错解决方法
帮同事安装gulp和webpack运行环境,使用cnpm install安装node-sass之后,运行项目总是报错,提示vendor目录不存在,几番百度之后,找到处理方法,这里记录一笔,防止以后遇到 ...