Problem overview
This is the first version of a small tr command. The method tr(vector<string> lines, string fromChar, string toChar) replaces every occurrence of one character with another in each line, then returns the lines joined by \n.
Both fromChar and toChar are strings that hold a single ASCII character, taken literally: no escape sequences and no ranges. Upper and lower case are different characters. A line may be empty or may not contain the character at all. With {"banana", "apple"}, fromChar = "a" and toChar = "X", the result is "bXnXnX\nXpple".
In the Unix tool, tr reads text and translates characters one by one. Here the text arrives as a vector of lines and the answer goes back as one string, which keeps the project easy to test. The statement limits the input to ASCII, and that matters in C++: a char is one byte, so a character outside ASCII, which takes several bytes in UTF-8, would be seen as several separate char values. With ASCII text, one byte is one character and the loops behave as expected.
Approach
The task is a character-by-character copy. Walk through the lines; inside each line walk through the characters; for each one, append either the replacement or the original character to a single result string. Nothing is modified in place, so the input stays intact and the function only builds new text.
Newlines go between the lines, not after them. Before every line except the first, the code appends "\n". This is the same "separator before every item but the first" pattern that works for any join, and it gives no newline at the start and none at the end.
The parameters arrive as strings, though they hold one character each. The characters themselves are fromChar[0] and toChar[0], the first character of each string. Comparing a char with fromChar[0] is a plain character comparison.
On the example, result is "bXnXnX" once the first line has been processed. The second pass through the outer loop first appends a newline and then the characters of "apple", which leaves "bXnXnX\nXpple".
Step by step
- Create an empty
stringnamedresult, where the output is built. - Loop over the lines with
int ifrom 0 whilei < lines.size(). - Add a newline when
i > 0, in a one-lineif. The first line gets none. - Loop over the characters of
lines[i]withint jfrom 0 whilej < lines[i].size(). - If
lines[i][j] == fromChar[0], appendtoChar[0]toresult. - Otherwise, in an
else, append the originallines[i][j]. - Return
resultafter both loops. The newlines are already in it.
The solution in C++
class Solution {
public:
string tr(vector<string> lines, string fromChar, string toChar) {
string result;
for (int i = 0; i < lines.size(); i++) {
if (i > 0) result += "\n";
for (int j = 0; j < lines[i].size(); j++) {
if (lines[i][j] == fromChar[0]) result += toChar[0];
else result += lines[i][j];
}
}
return result;
}
};
Points to watch:
- Two levels of indexing.
lines[i]is astring, solines[i][j]is onecharof it. The loop bounds use.size()of the right thing:lines.size()for the outer loop,lines[i].size()for the inner one. - Appending to a string.
result += "\n"appends a string literal,result += toChar[0]appends a singlechar. Both forms of+=work onstd::string. ifandelsewithout braces. Each branch has one statement, so braces are optional. If you add a second statement to a branch later, add the braces too.- Signed and unsigned.
size()returns an unsigned value andiis anint. The comparison works for these sizes because the index never goes negative.
A tidier version
Once the steps are clear, the same logic can be shorter: take the two characters out of the strings once, and use a range-based loop and the conditional operator.
char from = fromChar[0], to = toChar[0];
string result;
for (int i = 0; i < lines.size(); i++) {
if (i > 0) result += "\n";
for (char c : lines[i]) result += (c == from) ? to : c;
}
return result;
It returns the same "bXnXnX\nXpple" for the example. The lesson's version keeps the indexes visible, which is easier to follow while you are learning the loops.
Complexity
The code visits each character of each line once and does a constant amount of work per character, so the time is proportional to the total number of characters, O(N), plus one step per line for the newline. The result string holds a copy of the text, so the extra space is also O(N).
Edge cases and common mistakes
- Case matters.
{"Banana", "banana"}withfromChar = "B"andtoChar = "-"gives"-anana\nbanana": only the capitalBis replaced. - Empty lines.
{"", "abc"}with"a"and"z"gives"\nzbc". The empty line is kept, so the result starts with a newline. - No match.
{"hello"}with"z"and"y"returns"hello". - Spaces are characters too.
{"a b c"}with" "and"_"gives"a_b_c". - Comparing the whole string. Writing
lines[i][j] == fromCharcompares acharwith astring. The compiler rejects it with "no match for 'operator=='", because the two types can't be compared. UsefromChar[0]. - Replacing in place and forgetting the newlines. The output is one string, and the line breaks must be added as
"\n". - The same character on both sides.
{"x"}with"x"and"x"returns"x": replacing a character with itself changes nothing. - Empty input. An empty vector returns
"".
Testing
| lines | fromChar, toChar | result |
|---|---|---|
{"banana", "apple"} | "a", "X" | "bXnXnX\nXpple" |
{"Banana", "banana"} | "B", "-" | "-anana\nbanana" |
{"", "abc"} | "a", "z" | "\nzbc" |
{"a b c"} | " ", "_" | "a_b_c" |
{} | "a", "b" | "" |
The next version builds on this one.
