Start learning free

LESSON 394 OF 410 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: tr v2 — Set Translation in Java

Practice

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:

public String tr(List<String> lines, String set1, String set2)

Example:

Input: lines = ["banana", "cherry"], set1 = "abc", set2 = "ABC"

Output: "BAnAnA\nCherry"

When printed:
BAnAnA
Cherry

Build a Map<Character, Character> from each char in set1 to the matching char in set2. Then walk each line and use map.getOrDefault(ch, ch) to translate.

Map<Character, Character> map = new HashMap<>();
for (int i = 0; i < set1.length(); i++) {
    map.put(set1.charAt(i), set2.charAt(i));
}
// per char: map.getOrDefault(ch, ch)


The full solution:
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);
    }
}

STEP 1 OF 11
    Ctrl + Enter to check

    Tr V2 in Java

    Keep going with JavaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free