Build a tiny version of the Unix tr command. Given a list of lines and two single characters fromChar and toChar, replace every occurrence of fromChar with toChar in each line, then return the lines joined by newline characters (\n).
Notes: fromChar and toChar are single ASCII characters, taken literally (no escapes like \, no ranges). Upper and lower case are different characters. A line may be empty, and may not contain fromChar at all.
Function signature:
string tr(vector<string> lines, string fromChar, string toChar)
Example:
Input: lines = ["banana", "apple"], fromChar = "a", toChar = "X" Output: "bXnXnX\nXpple" When printed: bXnXnX Xpple
Walk each line character-by-character. For each char, append
toChar[0] if it equals fromChar[0], otherwise append the original character.
for (int j = 0; j < lines[i].size(); j++) {
if (lines[i][j] == fromChar[0]) result += toChar[0];
else result += lines[i][j];
}
The full solution:
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;
}
};
Free plan: 30 tutor messages. Premium is unlimited.
