Build a more powerful version of the Unix tr command. Given a list of lines and two equal-length strings set1 and set2, replace every character in each line that appears in set1 at index i with set2[i]. Characters not in set1 are unchanged. Return the lines joined by newline characters (\n).
Notes: set1 and set2 have the same length, contain only ASCII characters, and set1 has no repeated character. Characters are taken literally: there are no ranges like a-z. All replacements happen at once, so set1 = "ab", set2 = "ba" swaps the two letters. Lines may be empty.
Function signature:
func tr(_ lines: [String], _ set1: String, _ set2: String) -> String
Example:
Input: lines = ["banana", "cherry"], set1 = "abc", set2 = "ABC" Output: "BAnAnA\nCherry" When printed: BAnAnA Cherry
Build a
[Character: Character] dictionary from each char in set1 to the matching char in set2. Then walk each line and use map[ch] ?? ch to translate.
var map = [Character: Character]()
for (a, b) in zip(set1, set2) {
map[a] = b
}
// per char: map[ch] ?? ch
The full solution:
class Solution {
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")
}
}
Free plan: 30 tutor messages. Premium is unlimited.
