为有牺牲多壮志,敢教日月换新天。

[Swift]LeetCode988. 从叶结点开始的最小字符串 | Smallest String Starting From Leaf

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

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

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.

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

(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.)

 

Example 1:

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

Example 2:

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

Example 3:

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

Note:

  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',依此类推。

找出按字典序最小的字符串,该字符串从这棵树的一个叶结点开始,到根结点结束。

(小贴士:字符串中任何较短的前缀在字典序上都是较小的:例如,在字典序上 "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 }

 

posted @ 2019-02-04 13:32  为敢技术  阅读(256)  评论(0编辑  收藏  举报