Problem overview
The second version of the tr tool translates a whole set of characters at once. The method tr(List<String> lines, String set1, String set2) receives two strings of equal length. In each line, a character found in set1 at index i becomes set2.charAt(i). Characters that aren't in set1 stay as they are. The lines are joined by \n.
The strings are ASCII and have the same length, set1 has no repeated character, and characters are literal (no ranges such as a-z). All replacements happen at once, so set1 = "ab" with set2 = "ba" swaps the two letters. Lines may be empty.
For ["banana", "cherry"], set1 = "abc" and set2 = "ABC", the answer is "BAnAnA\nCherry".
The previous version swapped a single character. This one needs a lookup from each character to its replacement.
Approach: build a lookup, then translate character by character
A Map<Character, Character> stores the pairs: the key is a character to look for, the value is its replacement. Build it once from the two sets, then walk through every line and look up each character.
The "all at once" rule is the reason not to chain String.replace calls, one per pair. Replacing a with b and then b with a would turn the second step's input into a string that already contains the first step's output. For "abba" the chained replaces give aaaa. A character-by-character pass looks every character up in the original line, so each one is translated exactly once, and "abba" with "ab" and "ba" becomes baab.
Another way to translate a character is to search set1 with indexOf and read set2 at the position found. It works, but it scans set1 for every character of every line. The map does that work once, up front, and then each lookup takes constant time on average. With the short sets of this lesson the difference is small, but the map also reads more clearly: it says which character becomes which.
Per line, a StringBuilder collects the translated characters. append adds to its end, which is cheaper than gluing strings together with + over and over.
Tracing one line
With set1 = "abc" and set2 = "ABC" the map holds three pairs: a=A, b=B and c=C. Here is the builder after each character of "cherry":
j=0 ch=c sb=C
j=1 ch=h sb=Ch
j=2 ch=e sb=Che
j=3 ch=r sb=Cher
j=4 ch=r sb=Cherr
j=5 ch=y sb=Cherry
Only c has an entry in the map. Every other character falls back to itself, so the line comes out as Cherry.
Step by step
- Create
map, aMap<Character, Character>set to a newHashMap. - Loop over the positions of
set1withifrom 0 toset1.length() - 1. The same position is valid inset2, since the lengths are equal. - Store each pair with
map.put(set1.charAt(i), set2.charAt(i)). - Create
result, an empty list of strings for the translated lines. - Loop over the lines with a for-each loop that names each element
line. - Create a fresh
StringBuildernamedsbfor each line, so lines don't mix. - Loop over the positions of
linewithjfrom 0 toline.length() - 1. - Read the character at position
jinto acharnamedch. - Append the translation.
map.getOrDefault(ch, ch)returns the replacement, orchitself when the map has none, andsb.appendadds it. - After the inner loop, add
sb.toString()toresult. It runs once per line, so it sits outside the inner loop's braces. - After the outer loop, return
String.join("\n", result).
The solution in Java
class Solution {
public String tr(List<String> lines, String set1, String set2) {
Map<Character, Character> map = new HashMap<>();
for (int i = 0; i < set1.length(); i++) {
map.put(set1.charAt(i), set2.charAt(i));
}
List<String> result = new ArrayList<>();
for (String line : lines) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < line.length(); j++) {
char ch = line.charAt(j);
sb.append(map.getOrDefault(ch, ch));
}
result.add(sb.toString());
}
return String.join("\n", result);
}
}
Details worth knowing:
- Maps hold objects, not primitives. The type is
Character, the wrapper ofchar. Java converts between the two automatically (autoboxing), somap.put(set1.charAt(i), ...)andgetOrDefault(ch, ch)work with plaincharvalues. getversusgetOrDefault.map.get('z')returnsnullfor a missing key, and appendingnullwould add the textnullto the line.getOrDefault(ch, ch)gives the unchanged character instead.putreplaces an existing key. Ifset1repeated a character, the later pair would silently overwrite the earlier one. The lesson rules repeats out, so each character has exactly one replacement and the loop needs no check for it.charAtreturns achar. It reads the character at a 0-based position.- Imports.
List,ArrayList,MapandHashMapare injava.util.
Complexity
Time: O(m + t), where m is the length of set1 and t is the total number of characters in all lines. Building the map takes m insertions, and each character of the text costs one lookup, which takes constant time on average.
Space: O(m + t). The map holds at most m pairs, and the builders and the result hold the translated text.
Edge cases and common mistakes
- Swaps.
["abba"]with"ab"and"ba"gives"baab". Chainedreplacecalls giveaaaa. - Characters outside the set.
["hello world", ""]with"lo"and"01"gives"he001 w1r0d\n". The space is untouched, and the empty line stays as an empty line after the last\n. - Reusing one
StringBuilder. Creating it outside the line loop would glue all the lines into one. - Using
getwithout a default. Missing keys givenull. - Empty sets. With
set1andset2both empty, the map is empty and every line comes back unchanged, so["abc"]gives"abc".
Testing
["banana", "cherry"]with"abc","ABC"gives"BAnAnA\nCherry".["abba"]with"ab","ba"gives"baab".["hello world", ""]with"lo","01"gives"he001 w1r0d\n".["abc"]with"",""gives"abc".
