在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given a string
Return the string formed after mapping. It's guaranteed that a unique mapping will always exist.
Example 1: Input: s = "10#11#12" Output: "jkab" Explanation: "j" -> "10#" , "k" -> "11#" , "a" -> "1" , "b" -> "2". Example 2: Input: s = "1326#" Output: "acz" Example 3: Input: s = "25#" Output: "y" Example 4: Input: s = "12345678910#11#12#13#14#15#16#17#18#19#20#21#22#23#24#25#26#" Output: "abcdefghijklmnopqrstuvwxyz"
Constraints:
给你一个字符串
返回映射之后形成的新字符串。 题目数据保证映射始终唯一。
示例 1: 输入:s = "10#11#12" 输出:"jkab" 解释:"j" -> "10#" , "k" -> "11#" , "a" -> "1" , "b" -> "2". 示例 2: 输入:s = "1326#" 输出:"acz" 示例 3: 输入:s = "25#" 输出:"y" 示例 4: 输入:s = "12345678910#11#12#13#14#15#16#17#18#19#20#21#22#23#24#25#26#" 输出:"abcdefghijklmnopqrstuvwxyz"
提示:
Runtime: 4 ms Memory Usage: 21.1 MB
1 class Solution { 2 func freqAlphabets(_ s: String) -> String { 3 let s:[Character] = Array(s) 4 var res:String = String() 5 var i:Int = 0 6 while(i < s.count) 7 { 8 if i < s.count - 2 && s[i + 2] == "#" 9 { 10 //"j":106 , "0": 48 , "1":49 11 let num:Int = 106 + (Int(s[i].asciiValue!) - 49) * 10 + Int(s[i + 1].asciiValue!) - 48 12 res.append(num.ASCII) 13 i += 2 14 } 15 else 16 { 17 //a:97 , "1":49 18 let num:Int = 97 + Int(s[i].asciiValue! ) - 49 19 res.append(num.ASCII) 20 } 21 i += 1 22 } 23 return res 24 } 25 } 26 27 //Int扩展 28 extension Int 29 { 30 //Int转Character,ASCII值(定义大写为字符值) 31 var ASCII:Character 32 { 33 get {return Character(UnicodeScalar(self)!)} 34 } 35 } Runtime: 16 ms
Memory Usage: 21.3 MB
1 class Solution { 2 private let chars = Array<Character>(" abcdefghijklmnopqrstuvwxyz") 3 func freqAlphabets(_ s: String) -> String { 4 var ans = "" 5 var sCopy = s 6 while !sCopy.isEmpty { 7 if let index = sCopy.firstIndex(of: "#"), sCopy.distance(from: sCopy.startIndex, to: index) == 2 { 8 let indexStr = String(sCopy[sCopy.startIndex...sCopy.index(after: sCopy.startIndex) ]) 9 sCopy.removeFirst(3) 10 ans.append(chars[Int(indexStr)!]) 11 } else { 12 ans.append(chars[Int("\(sCopy.removeFirst())")!]) 13 } 14 } 15 return ans 16 } 17 }
|
请发表评论