在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Additive number is a string whose digits can form additive sequence. A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. Given a string containing only digits Note: Numbers in the additive sequence cannot have leading zeros, so sequence Example 1: Input: Example 2: Input: Follow up: 累加数是一个字符串,组成它的数字可以形成累加序列。 一个有效的累加序列必须至少包含 3 个数。除了最开始的两个数以外,字符串中的其他数都等于它之前两个数相加的和。 给定一个只包含数字 说明: 累加序列里的数不会以 0 开头,所以不会出现 示例 1: 输入: 示例 2: 输入: 进阶: 16ms 1 class Solution { 2 func isAdditiveNumber(_ num: String) -> Bool { 3 let array = [Character](num) 4 let n = array.count 5 if n < 3 { return false } 6 7 func helper(s1: String, s2: String, remain: String) -> Bool { 8 let one = Int(s1)! 9 let two = Int(s2)! 10 let next = "\(one + two)" 11 if next == remain { return true } 12 var newRemain = remain 13 if remain.hasPrefix(next) { 14 let range = remain.range(of: next)! 15 newRemain.replaceSubrange(range, with: "") 16 return helper(s1: s2, s2: next, remain: newRemain) 17 } else { 18 return false 19 } 20 } 21 22 //设第一个数是以i结尾的,第二个数是以j结尾的 23 for i in 0 ... (n - 1)/2 - 1 { //i只能取到一半以下的值 24 let one = String(array[0...i]) 25 if one != "0" && one.hasPrefix("0") { continue } 26 for j in i + 1 ... n - 2 - i { //j至少取一位,且 n - j >= i 27 let two = String(array[i+1 ... j]) 28 if two != "0" && two.hasPrefix("0") { continue } 29 let remain = String(array[j+1 ... n-1]) 30 if remain != "0" && remain.hasPrefix("0") { continue } 31 if helper(s1: one, s2: two, remain: remain) { 32 return true 33 } 34 } 35 } 36 return false 37 } 38 } 24ms 1 class Solution { 2 func isAdditiveNumber(_ num: String) -> Bool { 3 4 if num.count < 3 { 5 return false 6 } 7 8 let numArr = Array(num) 9 10 for i in 1..<numArr.count-1 { 11 for j in i+1..<numArr.count { 12 let f = String(numArr[0..<i]) 13 let s = String(numArr[i..<j]) 14 var fn = Int(f)! 15 var sn = Int(s)! 16 var ln = fn + sn 17 18 var l = "\(ln)" 19 var total = f + s + l 20 21 if (f.count > 1 && f.first == "0" )||(s.count > 1 && s.first == "0") { 22 continue 23 } 24 while total.count < num.count { 25 let totalArr = Array(total) 26 if totalArr != Array(numArr[0..<totalArr.count]) { 27 break 28 } 29 fn = sn 30 sn = ln 31 ln = fn + sn 32 l = "\(ln)" 33 total += l 34 } 35 if total == num { 36 return true 37 } 38 } 39 } 40 return false 41 } 42 }
|
请发表评论