forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path271-Encode-and-Decode-Strings.swift
More file actions
30 lines (27 loc) · 961 Bytes
/
271-Encode-and-Decode-Strings.swift
File metadata and controls
30 lines (27 loc) · 961 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Codec {
func encode(_ strs: [String]) -> String {
if strs.isEmpty { return "#" }
var counts = [String]()
for str in strs {
counts.append("\(str.count)")
}
return counts.joined(separator: ",") + "#" + strs.joined()
}
func decode(_ s: String) -> [String] {
if s == "#" { return [] }
let index = s.firstIndex(of: "#")!
let counts = String(s[s.startIndex...s.index(before: index)]).components(separatedBy: ",")
var sIndex = s.index(after: index)
var decodedStrings = [String]()
for count in counts {
let endIndex = s.index(sIndex, offsetBy: Int(count)! - 1)
if sIndex > endIndex {
decodedStrings.append("")
continue
}
decodedStrings.append(String(s[sIndex...endIndex]))
sIndex = s.index(after: endIndex)
}
return decodedStrings
}
}