Problem overview
The tr tool translates characters. In this first version, tr(lines, from_char, to_char) receives a list of lines and two strings, each holding a single ASCII character. It replaces every occurrence of from_char with to_char in every line and returns the lines joined by \n. The characters are taken literally, upper and lower case are different, and a line may be empty or may not contain from_char at all.
For ["banana", "apple"] with "a" and "X", the result is "bXnXnX\nXpple". Every a is swapped, not only the first one in each line, and the ps and l in apple are untouched.
Approach
The work is the same for each line, so the shape is: translate each line, collect the results, join them. The translation of one line is a single call to the string method replace, which finds every occurrence of a pattern and returns a new string with the replacement in its place. Writing the character loop by hand is possible, but replace already does exactly the required job, and it does it on the whole line at once.
Step by step
- Create
result, an emptyVec<String>, withlet mut, since lines will be added to it. - Loop over the lines with
for line in &lines. The&lends the vector to the loop, so eachlineis a reference to aString, one whole line, not one character. - Push the translated line.
line.replace(&from_char, &to_char)returns a newString, which goes straight intoresult. The original line is not changed. The two&lend the strings toreplaceinstead of giving them away. - After the loop, join the vector with
"\n". The separator goes between lines only, so there is no newline after the last one.
The solution in Rust
impl Solution {
fn tr(lines: Vec<String>, from_char: String, to_char: String) -> String {
let mut result: Vec<String> = Vec::new();
for line in &lines {
result.push(line.replace(&from_char, &to_char));
}
return result.join("\n");
}
}
Rust details:
- Why the borrows. The loop runs once per line but uses
from_charandto_charevery time. Passing them by value would move them into the first call and leave nothing for the next iteration. Passing&from_charlends them, so every iteration can use them again. for line in &linesagainstfor line in lines. The first only borrows the vector. The second moves it into the loop, after whichlinescouldn't be used again. This function doesn't needlinesafterwards, so both compile; the borrow is the more common habit.replacereturns a new string. Strings in Rust don't change under a method like this, andreplaceallocates a freshString. The line inlinesstays as it was.- Patterns.
replaceaccepts achar, a&stror a&Stringas the pattern. Because the lesson's arguments areStringvalues,&from_charis the natural way to pass them.
Complexity
Time: O(L), where L is the total number of characters in all lines, because each line is scanned once by replace and then copied into the joined result. Space: O(L) for the translated lines and the final string.
Edge cases and common mistakes
- Only the first occurrence. Some languages' replace functions change just the first match. Rust's
replacechanges all of them:"banana"becomes"bXnXnX". - Case. With
"a"and"X","Banana"becomes"BXnXnX". TheBis a different character and is unchanged. An uppercase"A"would not match any of the lowercase letters. - Empty and unaffected lines.
["Banana", "", "xyz"]gives"BXnXnX\n\nxyz". The empty line stays as an empty line between two newlines. - Special characters are literal.
["a.b.c"]with"."and"-"gives"a-b-c". The dot is just a dot here, not a wildcard, becausereplacelooks for the exact text. - Putting the
joininside the loop. It runs once, after all lines are translated, so it sits outside the loop's braces. - Forgetting the
&on the strings passed toreplacegives two compile errors: aStringisn't accepted as the pattern (the trait Pattern is not implemented for String), and the replacement must be a&str(expected &str, found String).
Testing
["banana", "apple"]with"a"and"X"gives"bXnXnX\nXpple".["Banana", "", "xyz"]with"a"and"X"gives"BXnXnX\n\nxyz".["a.b.c"]with"."and"-"gives"a-b-c".
