Problem overview
This version of tr mimics tr -s. The function trSqueeze takes a slice of lines and a string chars. In every line, a run of the same character that appears in chars collapses to a single occurrence. All other characters stay unchanged, and the lines are joined by "\n".
chars is a non-empty ASCII string taken literally, with no ranges. Upper and lower case differ. Only runs of one repeated character from chars are collapsed: a run of characters outside chars stays as it is, and so does a mixed run such as "ab" repeated. Lines may be empty. For ["aaabbb", "abaa"] with "a" the result is "abbb\naba": the as are squeezed and the bs are not, because b is not in chars.
Approach: skip a byte that repeats the one just kept
A repeat means "this byte equals the byte right before it, and that byte is one we squeeze". So the loop only has to remember the previous byte. Walk through a line byte by byte, and for each one:
- If it is in the squeeze set and equals the previous byte, skip it.
- Otherwise, keep it, and remember it as the new previous byte.
The first byte of a run is always kept, because nothing before it matches. Every later byte of the run equals its predecessor and is skipped. The set of squeezable characters is a map used as a set, as in the previous version. Each line is built in a strings.Builder, and the finished lines are joined at the end.
Step by step
- Create the set
squeezeasmake(map[byte]bool). All characters are ASCII, so a byte is one character. - Loop over the positions of
charswithi. - Mark each byte
chars[i]as a member withsqueeze[chars[i]] = true. - Create
result, an empty slice of strings. - Loop over the lines by position
i. - Declare a
strings.Buildernamedsbwithvar. It assembles a string piece by piece without the repeated copying that gluing with+causes. A new one per line keeps lines apart. - Declare
prevas abyteset to 0. At the start of a line nothing came before, soprevstarts as a value no line character is expected to equal. - Loop over the bytes of
lines[i]withj. - Read the current byte into
ch. - Test for a repeat:
squeeze[ch] && ch == prev. Both parts must hold: the byte is squeezable and it repeats the previous one. - If so,
continue. That jumps to the next byte, so this one is never written. - Otherwise write it:
sb.WriteByte(ch). - Set
prevtoch, so the next byte is compared with the last one kept. - After the inner loop, append
sb.String()toresult. This sits outside the inner loop, so it runs once per line. A line can end up empty and still goes into the output. - After the outer loop, return
strings.Join(result, "\n").
The solution in Go
func trSqueeze(lines []string, chars string) string {
squeeze := make(map[byte]bool)
for i := 0; i < len(chars); i++ {
squeeze[chars[i]] = true
}
result := []string{}
for i := 0; i < len(lines); i++ {
var sb strings.Builder
var prev byte = 0
for j := 0; j < len(lines[i]); j++ {
ch := lines[i][j]
if squeeze[ch] && ch == prev {
continue
}
sb.WriteByte(ch)
prev = ch
}
result = append(result, sb.String())
}
return strings.Join(result, "\n")
}
Go details to notice:
strings.Builderneeds no setup.var sb strings.Buildergives an empty builder whose zero value is ready to use.WriteByteappends one byte, andString()returns what was written. Building with a builder avoids copying the whole string on every addition.- Indexing a string gives a byte.
lines[i][j]andchars[i]arebytevalues, which is whysqueezeis amap[byte]boolandprevis abyte. - A missing key reads as
false.squeeze[ch]isfalsefor any byte that was never added, so no comma-ok form is needed. &&short-circuits. Ifsqueeze[ch]is false, the comparison withprevis not evaluated. Either way the result is the same here.continueskips the rest of the loop body, includingprev = ch. That is harmless becausechalready equalsprevat that point.var prev byte = 0states the type explicitly. It is the same asvar prev byte, since the zero value of a byte is 0.
Complexity
Time: O(k + L), where k is the length of chars and L the total number of bytes in the lines. Each byte costs one map lookup and at most one write, and the joins are linear.
Space: O(k + L) for the set, the builders and the output.
Edge cases and common mistakes
- Only squeezable characters collapse.
["aaabbb"]with"a"gives"abbb", and with"ab"gives"ab". - Squeeze the run, not the character.
["abab", "aAaA"]with"a"comes back unchanged: theas are never adjacent, andAis a different character. - Different squeezable characters don't merge.
["abba"]with"ab"gives"aba". The twobs collapse, butaandbnext to each other stay. - Spaces.
["a b c", "x"]with" "gives"a b c\nx". - Several runs in a line.
["", "mississippi"]with"sp"gives"\nmisisipi": thesspairs and theppcollapse, while the single letters are untouched. The empty first line stays. - Comparing with the wrong byte. If
prevwere updated only when a byte is in the set, a run broken up by another character would be treated as continuous. - Not resetting between lines. Declaring
sbandprevinside the outer loop gives each line a fresh start, so a line's last character can't affect the next line's first. - Empty input. An empty slice gives
"".
Testing
["aaabbb", "abaa"],"a"gives"abbb\naba".["aaabbb"],"ab"gives"ab".["aabb"],"b"gives"aab".["a b c", "x"]," "gives"a b c\nx".["abab", "aAaA"],"a"gives"abab\naAaA".["abba"],"ab"gives"aba".["", "mississippi"],"sp"gives"\nmisisipi".- An empty slice gives
"".
