在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
Return any permutation of Example : Input: S = "cba" T = "abcd" Output: "cbad" Explanation: "a", "b", "c" appear in S, so the order of "a", "b", "c" should be "c", "b", and "a". Since "d" does not appear in S, it can be at any position in T. "dcba", "cdba", "cbda" are also valid outputs. Note:
字符串
返回任意一种符合条件的字符串 示例: 输入: S = "cba" T = "abcd" 输出: "cbad" 解释: S中出现了字符 "a", "b", "c", 所以 "a", "b", "c" 的顺序应该是 "c", "b", "a". 由于 "d" 没有在S中出现, 它可以放在T的任意位置. "dcba", "cdba", "cbda" 都是合法的输出。 注意:
Runtime: 8 ms
Memory Usage: 19.8 MB
1 class Solution { 2 func customSortString(_ S: String, _ T: String) -> String { 3 var res:String = String() 4 var m:[Character:Int] = [Character:Int]() 5 for c in T 6 { 7 m[c,default:0] += 1 8 } 9 for c in S 10 { 11 let num:Int = m[c,default:0] 12 for _ in 0..<num 13 { 14 res.append(c) 15 } 16 m[c,default:0] = 0 17 } 18 for (key,val) in m 19 { 20 for _ in 0..<val 21 { 22 res.append(key) 23 } 24 } 25 return res 26 } 27 } 8ms 1 class Solution { 2 func customSortString(_ S: String, _ T: String) -> String { 3 var tMap: Dictionary<Character, Int> = [:] 4 for t in T { 5 if let v = tMap[t] { 6 tMap[t] = v + 1 7 } else { 8 tMap[t] = 1 9 } 10 } 11 12 var result = "" 13 for s in S { 14 if let v = tMap[s] { 15 result.append(String(repeating: s, count: v)) 16 tMap.removeValue(forKey: s) 17 } 18 } 19 20 for k in tMap.keys { 21 result.append(String(repeating: k, count: tMap[k]!)) 22 } 23 24 return result 25 } 26 } 24ms 1 class Solution { 2 func customSortString(_ S: String, _ T: String) -> String { 3 let map = S.enumerated().reduce(into: [:]) { $0[$1.1, default: 0] = $1.0 } 4 let character = T.sorted(by: { map[$0, default: Int.max] < map[$1, default: Int.max] }) 5 return String(character) 6 } 7 } 32ms 1 class Solution { 2 static func relativeCode(_ c: Character) -> Int { 3 return Int(c.unicodeScalars.first!.value - Character("a").unicodeScalars.first!.value) 4 } 5 func customSortString(_ S: String, _ T: String) -> String { 6 var order = [Int](repeating: -1, count: 26) 7 for (i, s) in S.enumerated() { 8 order[Solution.relativeCode(s)] = i 9 } 10 11 return String(T.sorted { 12 return order[Solution.relativeCode($0)] < order[Solution.relativeCode($1)] 13 }) 14 } 15 }
|
请发表评论