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:
func trSqueeze(lines []string, chars string) string
Example:
Input: lines = ["aaabbb", "abaa"], chars = "a" Output: "abbb\naba" When printed: abbb aba
Build a
map[byte]bool acting as a set of the squeeze characters. Walk each line tracking prev (the last byte you kept); skip the current byte only if it's in the set AND equals prev.
The full solution:
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")
}
Free plan: 30 tutor messages. Premium is unlimited.
