Problem overview
Version 4 of the tr project behaves like tr -s. The method trSqueeze(lines: List[String], chars: String): String collapses each run of the same character into a single occurrence, but only for characters that appear in chars. Other characters, including repeats of them, are unchanged. The lines are joined by \n.
With ["aaabbb", "abaa"] and chars = "a", the answer is "abbb\naba". The run of three a characters becomes one, the run of bbb stays, and the two a characters at the end of "abaa" become one. A run collapses only when it is made of one and the same character: with chars = "ab", the line "abab" has no run at all, so it stays "abab". Case matters, and lines may be empty.
Approach
Walk through each line once and decide, for each character, whether to keep it. A character is dropped only when two things hold: it is in chars, and it equals the character that was kept just before it. Everything else is kept.
That requires remembering the last kept character, prev. Scala has no continue statement, so the code states the opposite condition: keep the character when it is not in the set, or when it differs from prev. These two statements are exact opposites by De Morgan's law: "drop when in the set and equal to prev" is the same as "keep when not in the set or different from prev".
Step by step
- Create
squeezeaschars.toSet, a set holding each character of the string once. - Create
result, an emptyArrayBuffer[String], for the squeezed lines. - Loop over each
lineinlines. - Create a fresh
StringBuildernamedsbfor the characters this line keeps. - Create
var prev = '\u0000', the null character. It stands for "nothing kept yet" at the start of every line, and it is avarbecause it changes. - Loop over each character
chofline. - Write
if (!squeeze.contains(ch) || ch != prev), the keep condition. - Inside the
if, appendchtosb. - Still inside, set
prevtoch. It is always the last character kept, so the next character is compared with it. - After the inner loop, add
sb.toString()toresult, even if it is empty. - After the outer loop, return
result.mkString("\n"). As the last line of the method it needs noreturn.
The solution in Scala
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")
}
}
Details worth understanding:
chars.toSetturns a string into aSet[Char]. For"banana"it holds three members,b,aandn, andcontains('n')istrue. Here the set is immutable, which is fine because it is never changed.prevonly changes inside theif, that is, when a character is kept. A dropped character does not alter it, and it would be the same character anyway, so a long run is still compared against its own first member.'\u0000'is aCharliteral for the character with code 0. The solution relies on lines not containing the null character: such a character at the start of a line, when it is also inchars, would be taken for a repeat and dropped. For ordinary text, the first character of a line is always compared against something different.- Characters not in
charsare always kept and still updateprev. That is why"abab"withchars = "ab"is untouched: each character differs from the one before it. !=compares characters by value.
Tracing the example
For the line "aaabbb" with chars = "a", the set holds only a. Here is the inner loop, character by character:
| ch | kept | sb afterwards |
|---|---|---|
a | yes (first of its run) | a |
a | no (in the set, same as prev) | a |
a | no | a |
b | yes (not in the set) | ab |
b | yes | abb |
b | yes | abbb |
The result is "abbb": the run of a characters collapses, and the run of b characters stays whole because b is not in chars.
You might wonder whether prev should hold the last character kept or the last character seen. Here the two agree. A dropped character always equals prev, so recording it would change nothing, and every other character is kept and recorded. The lesson's wording, "the last character that went into sb", is the simplest to reason about.
Complexity
Building the set takes O(k) for k characters in chars. Processing takes O(N) for N characters over all lines, with one constant-time set check and one comparison per character. Extra space is O(k) for the set plus O(N) for the output.
Edge cases and common mistakes
- Several characters in
chars.["aabbaa", "abab", "aabb"]with"ab"gives"aba\nabab\nab". Each run collapses on its own, and"abab"has no runs. - Squeezing spaces.
["hello world"]with" "gives"hello world". - Only listed characters collapse. The same line with
"l"gives"helo world": the two l characters merge and the spaces remain. - Case.
["AAaa"]with"a"gives"AAa". The capitals are not in the set, and the two lowercase letters merge. - Empty lines.
["", "zzz"]with"z"gives"\nz". The empty line stays. - Carrying
prevacross lines. Declaringprevoutside the line loop would let a line's last character affect the next line's first. It is created inside the loop for that reason. - Empty list. The result is
"".
