在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings. Machine 1 (sender) has the function: string encode(vector<string> strs) { // ... your code return encoded_string; } Machine 2 (receiver) has the function: vector<string> decode(string s) { //... your code return strs; } So Machine 1 does: string encoded_string = encode(strs); and Machine 2 does: vector<string> strs2 = decode(encoded_string);
Implement the Note:
设计将字符串列表编码为字符串的算法。编码后的字符串通过网络发送,并被解码回原始的字符串列表。 机器1(发送器)具有以下功能: string encode(vector<string> strs) { // ... your code return encoded_string; } 机器2(接收器)具有以下功能: vector<string> decode(string s) { //... your code return strs; } 所以机器1: string encoded_string = encode(strs);
vector<string> strs2 = decode(encoded_string); 机器2中的strs2应与机器1中的strs相同。 实现编码和解码方法。 注:
Solution 1 class Codec 2 { 3 func encode(_ strs:inout [String]) -> String 4 { 5 var res:String = String() 6 for a in strs 7 { 8 res += (String(a.count) + "/" + a) 9 } 10 return res 11 } 12 13 func decode(_ s:String) -> [String] 14 { 15 var s = s 16 var res:[String] = [String]() 17 while(!s.isEmpty) 18 { 19 var found:Int = s.find("/") 20 var len:Int = Int(s.subString(0, found)) ?? 0 21 s = s.subString(found + 1) 22 res.append(s.subString(0, len)) 23 s = s.subString(len) 24 } 25 return res 26 } 27 } 28 29 extension String { 30 31 func find(_ char:Character) -> Int 32 { 33 var arr:[Character] = Array(self) 34 for i in 0..<arr.count 35 { 36 if arr[i] == char 37 { 38 return i 39 } 40 } 41 return -1 42 } 43 44 // 截取字符串:从index到结束处 45 // - Parameter index: 开始索引 46 // - Returns: 子字符串 47 func subString(_ index: Int) -> String { 48 let theIndex = self.index(self.endIndex, offsetBy: index - self.count) 49 return String(self[theIndex..<endIndex]) 50 } 51 52 // 截取字符串:指定索引和字符数 53 // - begin: 开始截取处索引 54 // - count: 截取的字符数量 55 func subString(_ begin:Int,_ count:Int) -> String { 56 let start = self.index(self.startIndex, offsetBy: max(0, begin)) 57 let end = self.index(self.startIndex, offsetBy: min(self.count, begin + count)) 58 return String(self[start..<end]) 59 } 60 }
|
请发表评论