Start learning free

LESSON 399 OF 414 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: tr v3 — Delete Chars (-d) in Scala

Practice

Build a version of the Unix tr -d command. Given a list of lines and a string chars, remove every character that appears in chars from each line, then return the lines joined by newline characters (\n).

Notes: chars is a non-empty ASCII string whose characters are taken literally (no ranges). Upper and lower case are different characters. A line can become empty after deleting, and then it stays as an empty line in the output.

Function signature:

def trDelete(lines: Array[String], chars: String): String

Example:

Input: lines = ["banana", "apple"], chars = "aeiou"

Output: "bnn\nppl"

When printed:
bnn
ppl

Put each character of chars into a mutable.HashSet[Char] for O(1) lookup. Walk every line and append characters that are NOT in the set.

The full solution:
class Solution {
    def trDelete(lines: Array[String], chars: String): String = {
        val set = scala.collection.mutable.HashSet[Char]()
        for (i <- 0 until chars.length) {
            set.add(chars(i))
        }
        val result = scala.collection.mutable.ArrayBuffer[String]()
        for (line <- lines) {
            val sb = new StringBuilder()
            for (j <- 0 until line.length) {
                val ch = line(j)
                if (!set.contains(ch)) {
                    sb.append(ch)
                }
            }
            result += sb.toString()
        }
        return result.mkString("\n")
    }
}

STEP 1 OF 12
    Ctrl + Enter to check

    Tr V3 in Scala

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