[Swift]LeetCode988. 從葉結點開始的最小字符串 | Smallest String Starting From Leaf

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-ojnkbzcy-md.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Given the root of a binary tree, each node has a value from 0 to 25 representing the letters 'a' to 'z': a value of 0 represents 'a', a value of 1 represents 'b', and so on.node

Find the lexicographically smallest string that starts at a leaf of this tree and ends at the root.git

(As a reminder, any shorter prefix of a string is lexicographically smaller: for example, "ab" is lexicographically smaller than "aba".  A leaf of a node is a node that has no children.)github

 

Example 1:微信

Input: [0,1,2,3,4,3,4]
Output: "dba" 

Example 2:app

Input: [25,1,3,1,3,0,2]
Output: "adz" 

Example 3:this

Input: [2,2,1,null,1,0,null,0]
Output: "abc"

Note:spa

  1. The number of nodes in the given tree will be between 1 and 1000.
  2. Each node in the tree will have a value between 0 and 25.

給定一顆根結點爲 root 的二叉樹,書中的每一個結點都有一個從 0 到 25 的值,分別表明字母 'a'到 'z':值 0 表明 'a',值 1 表明 'b',依此類推。code

找出按字典序最小的字符串,該字符串從這棵樹的一個葉結點開始,到根結點結束。htm

(小貼士:字符串中任何較短的前綴在字典序上都是較小的:例如,在字典序上 "ab" 比 "aba" 要小。葉結點是指沒有子結點的結點。)

 

示例 1:

輸入:[0,1,2,3,4,3,4]
輸出:"dba"

示例 2:

輸入:[25,1,3,1,3,0,2]
輸出:"adz"

示例 3:

輸入:[2,2,1,null,1,0,null,0]
輸出:"abc"

 

提示:

  1. 給定樹的結點數介於 1 和 1000 之間。
  2. 樹中的每一個結點都有一個介於 0 和 25 之間的值。

 Runtime: 24 ms

Memory Usage: 3.8 MB
 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 class Solution {
15     var ret:String = "~"
16     func smallestFromLeaf(_ root: TreeNode?) -> String {
17         dfs(root,"")
18         return ret
19     }
20         
21     func dfs(_ cur: TreeNode?,_ s: String)
22     {
23         var s = s
24         if cur == nil {return}
25         s = String((97 + cur!.val).ASCII) + s
26         if cur?.left == nil && cur?.right == nil
27         {
28             if s < ret {ret = s}
29         }
30         dfs(cur?.left, s)
31         dfs(cur?.right, s)
32     }
33 }
34     
35 //Int擴展方法  
36 extension Int
37 {
38     //屬性:ASCII值(定義大寫爲字符值)
39     var ASCII:Character 
40     {
41         get {return Character(UnicodeScalar(self)!)}
42     }
43 }

24ms
 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 class Solution {
15     func smallestFromLeaf(_ root: TreeNode?) -> String {
16     guard let root = root else {
17         return ""
18     }
19     
20     let left = smallestFromLeaf(root.left)
21     let right = smallestFromLeaf(root.right)
22         
23         if left == "" {
24         return right + convertIntToChar(val: root.val)
25     }
26     
27     if right == "" {
28         return left + convertIntToChar(val: root.val)
29     }
30     
31     return min(left + convertIntToChar(val: root.val), right + convertIntToChar(val: root.val))
32 }
33 
34 func convertIntToChar(val: Int) -> String {
35     return ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"][val]
36   }
37 }

28ms

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 class Solution {
15     func smallestFromLeaf(_ root: TreeNode?) -> String {
16         var dict: [Int: String] = [0: "a", 1: "b", 2: "c", 3: "d", 4: "e", 5: "f", 6: "g", 7: "h", 8: "i", 9: "j", 10: "k", 11: "l", 12: "m", 13: "n", 14: "o", 15: "p", 16: "q", 17: "r", 18: "s", 19: "t", 20: "u", 21: "v", 22: "w", 23: "x", 24: "y", 25: "z", ]
17         var lists: [String] = []
18         var maxDepth = 0
19         
20         if root?.left == nil && root?.right == nil {
21             return String(dict[root?.val ?? 0] ?? "")
22         }
23         
24         func search(_ node: TreeNode?, str: String) {
25             guard let node = node else {
26                 return
27             }
28             
29             var str = str
30 
31             str = "\(dict[node.val] ?? "")\(str)"
32 
33             if node.left == nil && node.right == nil && str.count > 1 {
34                 lists.append(str)
35             }
36             
37             search(node.left, str: str)
38             search(node.right, str: str)
39         }
40         
41         search(root, str: "")
42         
43         return lists.sorted().first ?? ""
44     }
45 }

32ms

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public var parent: TreeNode?   
 8  *     public init(_ val: Int) {
 9  *         self.val = val
10  *         self.left = nil
11  *         self.right = nil
12  *         self.parent = nil
13  *     }
14  * }
15  */
16 class Solution {
17     
18     func smallestFromLeaf(_ root: TreeNode?) -> String {
19         var ans = [String]()
20         smallestFromLeaf(root, "", &ans)
21         ans.sort()
22         return ans.count > 0 ? ans.first! : ""
23     }
24     
25     func smallestFromLeaf(_ root: TreeNode?, _ str: String, _ ans: inout [String]) {
26         guard let node = root else {
27             return
28         }
29         var str = str
30         str += String(Unicode.Scalar(97 + node.val)!)
31         if node.left == nil && node.right == nil {
32             var rs = String(str.reversed())
33             ans.append(rs)
34         }
35         
36         if let left = node.left {
37             smallestFromLeaf(left, str, &ans)
38         }
39         
40         if let right = node.right {
41             smallestFromLeaf(right, str, &ans)
42         }
43     }
44 }

40ms

 1 class Solution {
 2     func smallestFromLeaf(_ root: TreeNode?) -> String {
 3         var s = ""
 4         if root == nil {
 5             return ""
 6         }
 7         var q = [TreeNode]()
 8         q.append(root!)
 9         var strs = [String]()
10         var m = [Int:Character]()
11         for n in 0 ... 25 {
12             m[n] =
13             Character(Unicode.Scalar(n + Int("a".first!.unicodeScalars.first!.value))!)
14         }
15         strs.append("\(m[root!.val]!)")
16         var alStr = [String]()
17         while q.count > 0 {
18             var tq = [TreeNode]()
19             var ts = [String]()
20             while q.count > 0 {
21                 if let nd = q.popLast(), let s = strs.popLast() {
22                     var fl = false
23                     var fr = false
24                     if let nl = nd.left {
25                         tq.append(nl)
26                         ts.append(s + "\(m[nl.val]!)") 
27                     } else {
28                         fl = true
29                     }
30                     if let nr = nd.right {
31                         tq.append(nr)
32                         ts.append(s + "\(m[nr.val]!)") 
33                     } else {
34                         fr = true
35                     }
36                     if fl && fr {
37                         alStr.append(String(s.reversed()))
38                     } else if fl || fr {
39                         //alStr.append(String(s.reversed()))
40                     }
41                 }
42             }
43             strs = ts
44             q = tq
45         }
46         alStr.sort()
47         return alStr[0]
48     }
49 }
相關文章
相關標籤/搜索