Problem overview
Version 4 of the tr project copies the -s flag. trSqueeze(lines: List<String>, chars: String): String collapses every run of the same character into one occurrence, but only for characters that appear in chars. Everything else is unchanged. The lines are returned joined with \n.
Only runs of one repeated character are squeezed. Different characters next to each other aren't a run, and a run of a character that isn't in chars stays as it is. Case matters, and lines may be empty. For ["aaabbb", "abaa"] with chars = "a" the result is "abbb\naba": the a runs shrink, the b run stays.
Approach
While walking through a line, the code needs to know the character it handled last. If the current character is the same and is one of the squeeze characters, it is a repeat and gets skipped. Otherwise it is appended. This needs one variable, prev, holding the last character that was kept, and a set of the squeeze characters so the membership test is quick.
Comparing with the last kept character is the same as comparing with the previous character, because a skipped character is by definition equal to the one before it.
Step by step
- Build the set.
val squeeze = chars.toHashSet()turns the string into a set of its characters in one call. - Prepare the output.
resultis avalholdingmutableListOf<String>(). - Loop over the lines with
for (line in lines). - Create a builder per line.
val sb = StringBuilder()collects the characters this line keeps. - Create
prev.var prev = '\u0000', the null character, stands for "nothing came before". It is avarbecause it changes. It is reset for each line, since a run can't continue from one line into the next. - Loop over the characters with
for (ch in line). - Test for a repeat.
if (squeeze.contains(ch) && ch == prev)is true only when both hold: this character is one to squeeze, and it repeats the one before. - Skip it. Inside the
if,continuejumps to the next character, so this one is never appended. - Keep the others. After the
if,sb.append(ch)adds the character. The first character of a run always gets here, since itsprevis something else. - Update
prevtoch, so the next character is compared with this one. - Store the line. After the inner loop,
result.add(sb.toString()), once per line. - Join after the outer loop with
joinToString("\n").
The solution in Kotlin
class Solution {
fun trSqueeze(lines: List<String>, chars: String): String {
val squeeze = chars.toHashSet()
val result = mutableListOf<String>()
for (line in lines) {
val sb = StringBuilder()
var prev = '\u0000'
for (ch in line) {
if (squeeze.contains(ch) && ch == prev) {
continue
}
sb.append(ch)
prev = ch
}
result.add(sb.toString())
}
return result.joinToString("\n")
}
}
Kotlin details in this code
toHashSet()on aStringproduces aHashSet<Char>, with one member per distinct character. It replaces the loop that fills the set in the previous version.'\u0000'is aCharliteral. Single quotes make aChar, double quotes aString, and\u0000is the Unicode escape for the character with code 0. Becauseprevis initialised with aChar, Kotlin infers its type asChar, so no?ornullis needed.- The placeholder never matches real text. It only matters for the first character of a line, where
ch == prevmust be false. A normal letter is never equal to the null character, so the first character is always kept. continueends the current round of the innermost loop, here the loop over characters, and moves to the next character. It skips both theappendand the update ofprev, which is fine becauseprevalready equalsch.&&is short-circuit. The second test runs only if the first is true.
Tracing the examples
| Line | chars | Result |
|---|---|---|
"aaabbb" | "a" | abbb |
"abaa" | "a" | aba |
"aaabbb" | "ab" | ab |
"aabbaa" | "ab" | aba |
"aaAAaa" | "a" | aAAa |
In the second row the lone a at the start and the pair at the end are separated by a b, so each is its own run: the first stays, the pair shrinks to one. In the third row both letters are in chars, so both runs shrink. The last row shows that case matters: AA isn't squeezed when only lowercase a is listed, and the two a runs around it don't join into one, so the output is aAAa.
Complexity
Each character is visited once, with a constant-time set lookup on average, so the time is O(total characters) plus O(m) to build the set from chars. The extra space is the set and the output.
Edge cases and common mistakes
- Squeezing every repeat. Only characters from
charsare squeezed. In"aaabbb"with"a", thebbbstays. - Merging separated runs. Characters that come back after something else aren't repeats.
"abaa"keeps its firstaand itsband squeezes only the final pair. - Not resetting
prevfor each line. Declaring it outside the outer loop would let a line's last character affect the next line's first. It is declared inside the loop for that reason. - Empty lines. The inner loop never runs, the builder is empty, and the line stays in the output as an empty line. With
["aaabbb", "aabbaa", ""]and"ab"the result isab,aba, then an empty line. - Comparing with the wrong character. Updating
prevbefore the test, or not at all, makes the comparison meaningless.
