Start learning free

LESSON 400 OF 414 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: tr v4 — Squeeze Repeats (-s) in Scala

Practice

Build a version of the Unix tr -s command. Given a list of lines and a string chars, collapse consecutive runs of any character that appears in chars to a single occurrence. Other characters are unchanged. Return the lines joined by newline characters (\n).

Notes: chars is a non-empty ASCII string whose characters are taken literally (no ranges). Only runs of the same character from chars are collapsed; all other characters, and runs of characters not in chars, stay as they are. Upper and lower case are different characters. Lines may be empty.

Function signature:

def trSqueeze(lines: List[String], chars: String): String

Example:

Input: lines = ["aaabbb", "abaa"], chars = "a"

Output: "abbb\naba"

When printed:
abbb
aba

Build a Set of the squeeze characters with chars.toSet. Walk each line tracking prev (the last char you kept); keep the current char unless it's in the set AND equals prev.

The full solution:
class Solution {
    def trSqueeze(lines: List[String], chars: String): String = {
        val squeeze = chars.toSet
        val result = scala.collection.mutable.ArrayBuffer[String]()
        for (line <- lines) {
            val sb = new StringBuilder()
            var prev = '\u0000'
            for (ch <- line) {
                if (!squeeze.contains(ch) || ch != prev) {
                    sb.append(ch)
                    prev = ch
                }
            }
            result += sb.toString()
        }
        result.mkString("\n")
    }
}

STEP 1 OF 11
    Ctrl + Enter to check

    Tr V4 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