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:
string tr(vector<string> lines, string set1, string set2)
Example:
Input: lines = ["banana", "cherry"], set1 = "abc", set2 = "ABC" Output: "BAnAnA\nCherry" When printed: BAnAnA Cherry
Build an
unordered_map<char, char> from each char of set1 to the matching char of set2. Then walk each line and translate via map.count(ch) + map[ch].
unordered_map<char, char> map;
for (int i = 0; i < set1.size(); i++) {
map[set1[i]] = set2[i];
}
// per char: map.count(ch) ? map[ch] : ch
The full solution:
class Solution {
public:
string tr(vector<string> lines, string set1, string set2) {
unordered_map<char, char> map;
for (int i = 0; i < set1.size(); i++) {
map[set1[i]] = set2[i];
}
string result;
for (int i = 0; i < lines.size(); i++) {
if (i > 0) result += "\n";
for (int j = 0; j < lines[i].size(); j++) {
char ch = lines[i][j];
if (map.count(ch)) result += map[ch];
else result += ch;
}
}
return result;
}
};
Free plan: 30 tutor messages. Premium is unlimited.
