在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 给出长度相同的两个字符串: 等价字符遵循任何等价关系的一般规则:
例如, 利用 示例 1: 输入:A = "parker", B = "morris", S = "parser" 输出:"makkek" 解释:根据 示例 2: 输入:A = "hello", B = "world", S = "hold" 输出:"hdld" 解释:根据 示例 3: 输入:A = "leetcode", B = "programs", S = "sourcecode" 输出:"aauaaaaada" 解释:我们可以把 A 和 B 中的等价字符分为 提示:
64 ms 1 class Solution { 2 var f:[Int] = [Int](repeating:0,count:26) 3 func smallestEquivalentString(_ A: String, _ B: String, _ S: String) -> String { 4 var n:Int = A.count 5 var m:Int = S.count 6 var ans:String = String() 7 for i in 0..<26 8 { 9 f[i] = i 10 } 11 let arrA:[Int] = Array(A).map{$0.ascii - 97} 12 let arrB:[Int] = Array(B).map{$0.ascii - 97} 13 for i in 0..<n 14 { 15 merge(arrA[i],arrB[i]) 16 } 17 let arrS:[Int] = Array(S).map{$0.ascii - 97} 18 for i in 0..<m 19 { 20 ans.append((get(arrS[i]) + 97).ASCII) 21 } 22 return ans 23 } 24 25 func get(_ x:Int) -> Int 26 { 27 if f[x] == x 28 { 29 return x 30 } 31 f[x] = get(f[x]) 32 return f[x] 33 } 34 35 func merge(_ x:Int,_ y:Int) 36 { 37 var x = x 38 var y = y 39 x = get(x) 40 y = get(y) 41 if x < y 42 { 43 (x,y) = (y,x) 44 } 45 f[x] = y 46 } 47 } 48 49 //Character扩展 50 extension Character 51 { 52 //Character转ASCII整数值(定义小写为整数值) 53 var ascii: Int { 54 get { 55 return Int(self.unicodeScalars.first?.value ?? 0) 56 } 57 } 58 } 59 60 //Int扩展 61 extension Int 62 { 63 //Int转Character,ASCII值(定义大写为字符值) 64 var ASCII:Character 65 { 66 get {return Character(UnicodeScalar(self)!)} 67 } 68 }
|
请发表评论