Problem overview
The second version of tr translates a whole set of characters at once. tr(_ lines: [String], _ set1: String, _ set2: String) -> String receives two ASCII strings of equal length. Every character of a line found at index i of set1 becomes set2[i]; every other character stays. The lines are joined with "\n". Characters are literal, there are no ranges, and set1 has no repeats.
For ["banana", "cherry"], "abc" and "ABC" the result is "BAnAnA\nCherry".
The replacements happen all at once. With set1 = "ab" and set2 = "ba", the line "abba" becomes "baab": the letters swap places.
Approach: build a lookup table, then translate character by character
The previous version called one string method per line. That can't work for a set. Calling replacingOccurrences once per pair is wrong for a swap: "abba" with a to b first becomes "bbbb", and the second replacement then turns every b into a, giving "aaaa". The pairs interfere with each other.
The fix is to decide each character's fate in a single look. Build a dictionary from each character of set1 to its partner in set2. Then walk through the line once. For each character, ask the dictionary: if it has an entry, use the replacement, otherwise keep the character. Every character is judged from its original value, so there is no chain reaction.
A dictionary also keeps the work small. The alternative is to search set1 for every character of every line, which repeats the same scan again and again. Building the table once means each character costs a single lookup, however long the sets are.
Tracing one line
Take "banana" with set1 = "abc" and set2 = "ABC". The dictionary holds a to A, b to B and c to C. The loop over the line extends out one character at a time:
| Character | out afterwards |
|---|---|
b | B |
a | BA |
n | BAn |
a | BAnA |
n | BAnAn |
a | BAnAnA |
The letter n has no entry in the dictionary, so it is copied as it is. Every other letter is looked up in the original table, never in the text built so far, which is why a translation can't be translated twice.
Step by step
- Create the dictionary
map, typed[Character: Character], withvar. Keys are the characters to look for, values the replacements. - Loop over
zip(set1, set2)withaandbnaming each pair.zippairs up the characters at the same position. - Store
map[a] = binside the loop. - Create
result, an empty[String], for the translated lines. - Loop over
lineinlines. - Create
out, an empty string, inside the loop. A fresh one per line keeps lines from mixing. - Loop over
chinline. Iterating a string yields its characters one at a time. - Add the replacement
String(map[ch] ?? ch)toout. - Append
outtoresultafter the inner loop, once per line. - Return the joined lines after the outer loop.
The solution in Swift
func tr(_ lines: [String], _ set1: String, _ set2: String) -> String {
var map = [Character: Character]()
for (a, b) in zip(set1, set2) {
map[a] = b
}
var result = [String]()
for line in lines {
var out = ""
for ch in line {
out += String(map[ch] ?? ch)
}
result.append(out)
}
return result.joined(separator: "\n")
}
Details that matter:
CharacterversusString. Looping over a string givesCharactervalues, so the dictionary is keyed byCharacter. The finalString(...)turns a character into a string so that+=can append it toout.- Dictionary lookups are optional.
map[ch]has typeCharacter?: it isnilwhenchis not a key. For example, with["a": "b"],map["a"]isOptional("b")andmap["z"]isnil. - The
??operator.x ?? ygives the unwrappedxwhen it has a value, otherwisey. Here it falls back to the original character, so unlisted characters stay put. zipand unequal lengths.zipstops at the shorter sequence. The lesson guarantees equal lengths, so no pair is lost.- Repeated keys. Assigning
map[a] = bfor a key that already exists overwrites the old value. The lesson promises thatset1has no repeats, so this never happens in its tests. If it did, the pair that comes last would win: with"aa"and"XY",map["a"]ends up asOptional("Y"). - What a
Characteris. Swift'sCharacteris one user-visible character, which can be made of several Unicode scalars. The text"e"followed by a combining accent hascount1 and two Unicode scalars. The lesson's input is plain ASCII, where each character is a single scalar, so the distinction doesn't show up. - Tuple destructuring.
for (a, b) in zip(...)unpacks each pair into two names.
Complexity
Time: O(k + m), where k is the length of set1 and m the total number of characters in all lines. Building the table takes k steps, and each character of a line costs one average-constant-time dictionary lookup. Space: O(k + m) for the table and the translated output.
Edge cases and common mistakes
- Swaps.
["abba"]with"ab"and"ba"returns"baab". Chaining one replacement after another would turn it into"aaaa". - Characters outside
set1. They are kept as they are:["hello world"]with"lo"and"01"returns"he001 w1r0d", and the space stays. - Empty lines.
["", "xyz"]with"abc"and"ABC"returns"\nxyz". The empty line stays in place. - Case.
"a"and"A"are different keys. - Forgetting
String(...). Adding aCharacterto aStringwith+=doesn't compile. The conversion is required.
Testing
["banana", "cherry"],"abc","ABC"gives"BAnAnA\nCherry".["abba"],"ab","ba"gives"baab".["hello world"],"lo","01"gives"he001 w1r0d".["", "xyz"],"abc","ABC"gives"\nxyz".
