zoukankan      html  css  js  c++  java
  • 388. Longest Absolute File Path

    package LeetCode_388
    
    import java.util.*
    /**
     * 388. Longest Absolute File Path
     * https://leetcode.com/problems/longest-absolute-file-path/description/
     *
     * We will represent the file system as a string where "
    	" mean a subdirectory of the main directory,
     * "
    		" means a subdirectory of the subdirectory of the main directory and so on.
     * Each folder will be represented as a string of letters and/or digits.
     * Each file will be in the form "s1.s2" where s1 and s2 are strings of letters and/or digits.
    For example,
    the file system above is represented as "dir
    	subdir1
    		file1.ext
    		subsubdir1
    	subdir2
    		subsubdir2
    			file2.ext".
    Given a string input representing the file system in the explained format,
    return the length of the longest absolute path to a file in the abstracted file system.
    If there is no file in the system, return 0.
    
    Constraints:
    1. 1 <= input.length <= 104
    2. input may contain lower-case or upper-case English letters, a new line character '
    ',
    a tab character '	', a dot '.', a space ' ' or digits.
     * */
    class Solution {
        /*
        * solution: Stack, save all the length of candidate in stack, Time complexity:O(n), Space complexity:O(n)
        * */
        fun lengthLongestPath(input: String): Int {
            var result = 0
            //save all the length
            val stack = Stack<Int>()
            val stringList = input.split("
    ")
            for (path in stringList) {
                //last index of 	 is current line's level
                val level = path.lastIndexOf("	") + 1
                //try to find its parent, when stack size == level, the pop one is parent
                while (stack.size > level) {
                    stack.pop()
                }
                val parent = if (stack.isEmpty()) 0 else stack.peek() + 1
                //push a new candidate
                val newLen = parent + path.length - level
                stack.push(newLen)
                //if is file
                if (path.contains(".")) {
                    result = Math.max(result, newLen)
                }
            }
            return result
        }
    
    }
  • 相关阅读:
    随堂作业——到底有几个“1”(C++)
    《你的灯亮着吗》读书笔记3
    《你的灯亮着吗》读书笔记2
    软件工程随堂小作业——寻找“水桶”(C++)
    《你的灯亮着吗》读书笔记1
    《梦断代码》阅读笔记一
    软件工程课堂练习--四则运算(三)
    软件工程课堂练习--结对初体验
    软件工程课堂练习--四则运算单元测试
    软件工程课堂练习四则运算续篇
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13766769.html
Copyright © 2011-2022 走看看