[Swift]LeetCode388. 文件的最长绝对路径 | Longest Absolute File Path

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9778434.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

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 subdir2subdir1 contains a file file1.ext and an empty second-level sub-directory subsubdir1subdir2 contains a second-level sub-directory subsubdir2containing 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.


 假设我们以下述方式将我们的文件系统抽象成一个字符串:

字符串 "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" 表示:

dir
    subdir1
    subdir2
        file.ext

目录 dir 包含一个空的子目录 subdir1 和一个包含一个文件 file.ext 的子目录 subdir2 。

字符串 "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext" 表示:

dir
    subdir1
        file1.ext
        subsubdir1
    subdir2
        subsubdir2
            file2.ext

目录 dir 包含两个子目录 subdir1 和 subdir2。 subdir1 包含一个文件 file1.ext 和一个空的二级子目录 subsubdir1subdir2 包含一个二级子目录 subsubdir2 ,其中包含一个文件 file2.ext

我们致力于寻找我们文件系统中文件的最长 (按字符的数量统计) 绝对路径。例如,在上述的第二个例子中,最长路径为 "dir/subdir2/subsubdir2/file2.ext",其长度为 32 (不包含双引号)。

给定一个以上述格式表示文件系统的字符串,返回文件系统中文件的最长绝对路径的长度。 如果系统中没有文件,返回 0

说明:

  • 文件名至少存在一个 . 和一个扩展名。
  • 目录或者子目录的名字不能包含 .

要求时间复杂度为 O(n) ,其中 n 是输入字符串的大小。

请注意,如果存在路径 aaaaaaaaaaaaaaaaaaaaa/sth.png 的话,那么  a/aa/aaa/file1.txt 就不是一个最长的路径。


 16ms

 1 class Solution {
 2     func lengthLongestPath(_ input: String) -> Int {
 3         guard input != nil || input.count != 0 else
 4         {
 5             return 0
 6         }
 7         //创建整形堆栈,存放各级文件长度
 8         var stackOfLen = Stack<Int>()
 9         var strArray = input.characters.split{$0 == "\n"}.map(String.init)
10         var longesLen:Int = 0
11         for i in 0..<strArray.count
12         {
13             let item:String = strArray[i]
14             ////计算当前文件的层级
15             var level = LastIndexOf(item)
16             //返回到上一个同级文件的位置,注意使用count(),而非count
17             //例如:示例中遇到 \tsubdir2 时返回到与它同级的 \tsubdir1 位置
18             while(stackOfLen.count() > level)
19             {
20                 stackOfLen.pop()
21             }
22             let tempLen:Int = item.count - level
23             if stackOfLen.count() == 0
24             {
25                 stackOfLen.push(tempLen)
26             }
27             else
28             {
29                 ////加1 是返回的结果带有 / 分割
30                 let num:Int = tempLen + stackOfLen.GetLastElement() + 1
31                 stackOfLen.push(num)
32             }
33             if item.contains(".")
34             {                
35                 longesLen = max(longesLen,stackOfLen.GetLastElement())
36             }     
37         }
38         return  longesLen
39     }
40     //获取最后一个"\t"的索引整数位置
41     func LastIndexOf(_ item:String) -> Int
42     {
43         var num:Int = 0
44         var itemReversed:ReversedCollection<String> = item.reversed()
45         for i in 0..<itemReversed.count
46         {
47             var char:Character = itemReversed[itemReversed.index(itemReversed.startIndex, offsetBy: i)]
48             if  char == "\t"
49             {
50                 //注意索引也要反转,返回的为索引位置+1
51                 num = item.count - i
52                 break
53             }
54         }
55         return num
56     }
57         
58     //堆栈的泛型通用版本
59     struct Stack<Element> {
60         var items = [Element]()
61         //入栈
62         //mutating 关键字修饰方法是为了能在该方法中修改 struct 或是 enum 的变量
63         mutating func push(_ item: Element) {
64             items.append(item)
65         }
66         //出栈
67         mutating func pop() -> Element {
68             return items.removeLast()
69         }
70         //返回堆栈中的元素个数
71         mutating func count() -> Int
72         {
73             return items.count
74         }
75         //获取最后一个元素
76         mutating func GetLastElement()->Element
77         {
78             return items[items.count-1]
79         }
80     }
81 }

8ms

 1 class Solution {
 2     
 3     func lengthLongestPath(_ input: String) -> Int {
 4         guard !input.isEmpty else { return 0 }
 5         
 6         let lines = input.split(separator: "\n").map{ String($0) }
 7         var sum = [Int](repeating: 0, count: input.count + 1)
 8         var result = 0
 9         
10         for line in lines {
11             var count = 0 
12             while line.charAt(count) == "\t" {
13                 count += 1
14             }
15             let level = count + 1
16             let len = line.count - (level - 1)
17             if line.contains(".") {
18                 result = max(result, sum[level - 1] + len + level - 1)
19             } else {
20                 sum[level] = sum[level - 1] + len
21             }
22         }
23         
24         return result 
25     }
26 }
27 
28 extension String {
29     
30     func charAt(_ i: Int) -> Character {
31         let index = self.index(self.startIndex, offsetBy: i)
32         return self[index]
33     }
34 }

12ms

 1 class Solution {
 2     func lengthLongestPath(_ input: String) -> Int {
 3         var dirPathLengths = [Int]()
 4         var maxLength = 0
 5         for pathComponent in input.split(separator: "\n") {
 6             var dirLength = 0
 7             let isFile = pathComponent.contains(".")
 8             for (depth, dirLevel) in pathComponent.split(separator: "\t", omittingEmptySubsequences: false).enumerated() {
 9                 let isPathComponentFile = dirLevel.contains(".")
10                 if depth < dirPathLengths.count {
11                     if !dirLevel.isEmpty && !isFile {
12                         dirPathLengths[depth] = dirLevel.count
13                     }
14                 } else {
15                     if !dirLevel.isEmpty && !isFile {
16                         dirPathLengths.append(dirLevel.count)
17                     }
18                 }
19                 if isFile {
20                     dirLength += (isPathComponentFile ? pathComponent.count : dirPathLengths[depth])
21                 }
22             }
23             maxLength = max(maxLength, dirLength)
24         }
25         return maxLength
26     }
27 }

16ms

 1 class Solution {
 2     
 3     func lengthLongestPath(_ input: String) -> Int {
 4         guard !input.isEmpty else { return 0 }
 5         
 6         let lines = input.split(separator: "\n").map{ String($0) }
 7         var sum = [Int](repeating: 0, count: input.count + 1)
 8         var result = 0
 9         
10         for line in lines {
11             var count = 0 
12             while line.charAt(count) == "\t" {
13                 count += 1
14             }
15             let level = count + 1
16             let len = line.count - (level - 1)
17             if line.contains(".") {
18                 result = max(result, sum[level - 1] + len + level - 1)  // Plus "/"
19             } else {
20                 sum[level] = sum[level - 1] + len
21             }
22         }
23         
24         return result 
25     }
26 }
27 
28 extension String {
29     
30     func charAt(_ i: Int) -> Character {
31         let index = self.index(self.startIndex, offsetBy: i)
32         return self[index]
33     }
34 }

 

转载于:https://www.cnblogs.com/strengthen/p/9778434.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值