[Swift Weekly Contest 122]LeetCode988. 从叶结点开始的最小字
Given the? 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,? ? Example 1: Input: [0,1,2,3,4,4]
Output: "dba"
Example 2: Input: [25,2]
Output: "adz"
Example 3: Input: [2,null,0]
Output: "abc"
Note:
给定一颗根结点为? 找出按字典序最小的字符串,该字符串从这棵树的一个叶结点开始,到根结点结束。 (小贴士:字符串中任何较短的前缀在字典序上都是较小的:例如,在字典序上? ? 示例 1: 输入:[0,4] 输出:"dba" 示例 2: 输入:[25,2] 输出:"adz" 示例 3: 输入:[2,0] 输出:"abc" ? 提示:
?
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 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |