Longest Absolute File Path

规则的理解极其麻烦,首先这里的转义字符不论是n还是t都是不能算进字符长度的,然后如果一个路径不包含真正的文件名我们也是不能计算它的长度的,简而言之就是没有.的路径我们都不用计算长度,最后.本身也是需要计算的,另外路径之间的分隔斜杠也是需要计算进去的,没有用九章的思路,正则表达式实在难懂

class Solution(object):
    def lengthLongestPath(self, input):
        """
        :type input: str
        :rtype: int
        """
        lst = input.split('\n')
        stack = []
        result = 0

        for dire in lst:
            cur = 0
            while dire and dire[cur] == '\t':
                cur += 1

            while stack and len(stack) - 1 >= cur:
                stack.pop()

            stack.append(dire[cur : ])
            if '.' in dire:
                result = max(result, self.length(stack))

        return result

    def length(self, stack):
        result = len(stack) - 1
        for word in stack:
            result += len(word)
        return result

一个更简洁的版本,此题需要记住的就是转义字符长度都为1

class Solution(object):
    def lengthLongestPath(self, input):
        """
        :type input: str
        :rtype: int
        """
        stringList = input.split('\n')
        stack = []
        result = 0

        for string in stringList:
            countOfTab = string.count('\t')
            tmpString = string[countOfTab:]
            while countOfTab < len(stack):
                stack.pop()
            stack.append(tmpString)
            if tmpString.find('.') != -1:
                result = max(result, len('/'.join(stack)))

        return result

results matching ""

    No results matching ""