Problem overview
Version 2 of tr translates whole sets of characters. tr(lines, set1, set2) receives lines and two strings of equal length. Each character of a line that appears in set1 at index i becomes the character at index i of set2. Other characters stay. The lines are joined by \n. The sets hold only ASCII characters, set1 has no repeats, characters are literal (no ranges such as a-z), and lines may be empty. The previous version swapped a single character.
For ["banana", "cherry"] with set1 = "abc" and set2 = "ABC", the result is "BAnAnA\nCherry": a becomes A, b becomes B, c becomes C, and the other letters are untouched.
Approach
Looping over set1 for every character of every line would work, but a lookup table is cleaner. Build a HashMap once, with each character of set1 as a key and its partner from set2 as the value. Then walk over every line character by character, look each character up, and push either its replacement or the character itself.
Because every character is looked up in the original table and written to a separate output string, all replacements happen at once. With set1 = "ab" and set2 = "ba", the line "abba" becomes "baab": the new b produced from an a is never translated again. A chain of one-after-another replace calls would not have this property: "abba".replace("a", "b").replace("b", "a") gives "aaaa", because the second call also changes the b characters the first call just created. That is why the table is built first and applied in a single pass.
On the example, the table holds three pairs: a to A, b to B and c to C. For "banana" the lookups go b found (B), a found (A), n not found (stays n), then a, n, a again, which builds "BAnAnA" exactly as the example expects. In "cherry" only the leading c is in the table, so the result is "Cherry".
Step by step
- Create
map, an emptyHashMap, withlet mut. It records which character becomes which. - Loop over both sets together.
set1.chars().zip(set2.chars())pairs the characters at the same position, and(a, b)names each pair. - Insert the pair with
insert(a, b): the key is the character to look for, the value its replacement. - Create
result, an empty vector for the translated lines. - Loop over the lines with
for line in lines. - Create
out, a fresh emptyStringfor the line being translated, so lines don't mix. - Loop over the characters of the line with
line.chars(). - Push the replacement or the character itself, using the lookup expression explained below.
- Push
outontoresultafter the inner loop, once per line. - Join the lines with
"\n"after the outer loop.
The solution in Rust
impl Solution {
fn tr(lines: Vec<String>, set1: String, set2: String) -> String {
let mut map = HashMap::new();
for (a, b) in set1.chars().zip(set2.chars()) {
map.insert(a, b);
}
let mut result = Vec::new();
for line in lines {
let mut out = String::new();
for ch in line.chars() {
out.push(*map.get(&ch).unwrap_or(&ch));
}
result.push(out);
}
return result.join("\n");
}
}
Rust details:
- Inferred types. The map and the vector have no type annotations. Rust works out
HashMap<char, char>from theinsertcall andVec<String>from thepushcall. In a standalone program,HashMapcomes fromstd::collectionsand needsuse std::collections::HashMap;at the top. - Characters, not bytes.
chars()yieldscharvalues, so the code works on whole characters. For the ASCII text in this task, that is the same as bytes. - The lookup line.
map.get(&ch)returns anOption<&char>: a reference to the stored replacement, orNone.unwrap_or(&ch)supplies a reference tochitself when the key is absent. Both branches are references, so the*in front copies thecharout of whichever one is chosen.charis a smallCopytype, so that is cheap. zipstops at the shorter side. With equal lengths, as promised, nothing is lost. With unequal lengths, the extra characters of the longer set would be ignored without any error.- Moving the lines.
for line in linesconsumes the vector, which is fine becauselinesisn't used after the loop.
Complexity
Time: O(S + L), where S is the length of the sets and L the total number of characters in the lines. Building the map takes S insertions, and each line character costs one average-constant-time lookup. Space: O(S + L) for the table, the translated lines and the joined result.
Edge cases and common mistakes
- Swapping letters.
["abba", "cab"]with"ab"and"ba"gives"baab\ncba". Translating in one pass is what makes a swap work. - Empty lines. Nothing is looked up in an empty line.
["", "Hello"]with"l"and"L"gives"\nHeLLo". The empty line stays an empty line. - Case.
'a'and'A'are different keys. With"abc"and"ABC", an uppercaseAin the input stays as it is. - Empty sets. With
""and""the map stays empty and the lines come out unchanged. - Forgetting the
*.out.push(map.get(&ch).unwrap_or(&ch))tries to push a&charwhere acharis expected, and the compiler reportsexpected char, found &char. - Mixing up key and value. The character found in
set1is the key, because that is what you look up in the lines.
Testing
["banana", "cherry"]with"abc"and"ABC"gives"BAnAnA\nCherry".["abba", "cab"]with"ab"and"ba"gives"baab\ncba".["", "Hello"]with"l"and"L"gives"\nHeLLo".["abc"]with""and""gives"abc".
